[英]Sum dataframe column that contains different data types
我有一個具有2列(id和rate)的數據幀(df),如下所示:
id rate
0 #NAME?
1 #NAME?
2 #NAME?
3 #NAME?
4 #NAME?
5 #NAME?
6 #NAME?
7 #NAME?
8 #NAME?
9 0.5
10 #NAME?
: :
211 0.25
212 0.00
213 #NAME?
214 1.00
215 #NAME?
如您所見,“ rate
列具有不止一種類型,我正在嘗試對非#NAME求和? 費率列中的條目。 我努力了:
df = pd.read_csv(full_path, header=0, usecols=[0,8], dayfirst=True,index_col=[0], names=['id', 'rate'])
print(df)
sumRate = sumRate + df['rate'].sum()
但我得到了以下異常:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
我不確定如何僅對浮點值求和,不幸的是,我要拉入數據幀的數據格式超出了我的控制范圍。
我認為您需要to_numeric
具有error='coerce'
參數的to_numeric
來將非數字首先轉換為NaN
,然后求和:
print (pd.to_numeric(df['rate'], errors='coerce'))
0 NaN
1 NaN
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN
9 0.50
10 NaN
11 NaN
12 0.25
13 0.00
14 NaN
15 1.00
16 NaN
Name: rate, dtype: float64
sumRate = pd.to_numeric(df['rate'], errors='coerce').sum()
print (sumRate)
1.75
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.