我有一個原始的 .csv 檔案,pandas 正在按預期讀取該檔案,并且該檔案的修剪版本洗掉了重復的行,其他所有內容都相同。然而,pandas 正在將第二個檔案中的數值作為字串讀取,并且無法對資料幀執行數學運算。
df1 = pd.read_csv("file1.csv")
print(df1)
df1 = (df1 - df1.min())/(df1.max() - df1.min())
attr1 attr2 attr3 ... attr7 attr attr9
0 0.384 0.0893 -30.439 ... 75.499 140417 0
... ... ... ... ... ... ... ...
2109 0.745 0.5430 -8.137 ... 139.964 185267 1
[2110 rows x 11 columns]
Process finished with exit code 0
.
df2 = pd.read_csv("file2.csv")
print(df2)
df2 = (df2 - df2.min())/(df2.max() - df2.min())
attr1 attr2 attr3 ... attr7 attr8 attr9
0 0.866 0.7300 -8.201 ... 118.523 379266 2
.. ... ... ... ... ... ... ...
1853 0.377 0.0156 -28.435 ... 140.179 186331 0
[1853 rows x 11 columns]
TypeError: unsupported operand type(s) for -: 'str' and 'str'
uj5u.com熱心網友回復:
該函式pd.read_csv將dtype其作為輸入,以便您可以指定每列的型別。例如:
pd.read_csv('file1.csv', dtype={variable1: 'float'})
會將列variable1作為浮動型別讀取。
或者,您可以dtype在讀取檔案后指定,如下所示:
df1['variable1'] = df1['variable1'].astype(float)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/515544.html
標籤:Python熊猫CSV
