我有一個充滿字串的資料框,我寧愿將其作為整數,或者在不可能的情況下浮動。
我已經嘗試使用try: except:.
字串"30"變成整數,但字串"40.0"變成浮點數。我希望一列僅包含整數作為字串 ( "35.0", "41.0", "55.0") 成為整數。
這是我嘗試過的一個版本:
import pandas as pd
data = {
'Name':['Tom', 'Dick', 'Harry'],
'Age':['20', '21', '19'],
'Height':['1.73', '1.80', '1.59'],
'Score':['72.0', '69.0', '68.0']
}
df = pd.DataFrame(data)
# Make list for looping through columns
cols = df.columns
# Check data types before manipulation
print(df.dtypes)
# Change to integer, or where not possible, float
for col in cols:
try:
df[col] = df[col].astype('int')
continue
except ValueError:
pass
try:
df[col] = df[col].astype('float')
except ValueError:
pass
# Check if manipulation was successful
print(df.dtypes)
uj5u.com熱心網友回復:
正如邁克爾已經評論過的,您可以使用pd.to_numericwith errors ignore。
for col in cols:
df[col] = pd.to_numeric(df[col], errors='ignore')
那時不需要嘗試例外。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/412136.html
標籤:
