我有一个数据框:
Event Modelled flow (cfs) Observed Flow (cfs)
Event 01 0.8610723 2.105263
Event 01 0.8596087 2.383901
Event 01 0.8749821 2.092879
Event 01 0.9045072 2.119195
Event 01 0.9267832 2.156347
Event 01 0.9156083 1.883901
我希望通过将现有列乘以值300来添加2个新列,如下所示:
df['Modelled Volume(f3)'] = df['Modelled Flow (cfs)']*300.00
df['Observed Volume(f3)'] = df['Observed Flow (cfs)']*300.00
如果我使用上述代码,我会收到以下错误:
TypeError: can't multiply sequence by non-int of type 'float'
我如何纠正这个问题?
答案 0 :(得分:1)
首先尝试施放到float
:
df['Modelled Volume(f3)'] = df['Modelled flow (cfs)'].astype(float)*300.00
df['Observed Volume(f3)'] = df['Observed Flow (cfs)'].astype(float)*300.00
print (df)
Event Modelled flow (cfs) Observed Flow (cfs) Modelled Volume(f3) \
0 Event 01 0.861072 2.105263 258.32169
1 Event 01 0.859609 2.383901 257.88261
2 Event 01 0.874982 2.092879 262.49463
3 Event 01 0.904507 2.119195 271.35216
4 Event 01 0.926783 2.156347 278.03496
5 Event 01 0.915608 1.883901 274.68249
Observed Volume(f3)
0 631.5789
1 715.1703
2 627.8637
3 635.7585
4 646.9041
5 565.1703
如果第一个解决方案失败,请将带有参数errors='coerce'
的列to_numeric
转换为有问题的值替换为NaN
:
df['Modelled Volume(f3)'] = pd.to_numeric(df['Modelled flow (cfs)'], errors='coerce')*300.00
df['Observed Volume(f3)'] = pd.to_numeric(df['Observed Flow (cfs)'], errors='coerce')*300.00
print (df)
Event Modelled flow (cfs) Observed Flow (cfs) Modelled Volume(f3) \
0 Event 01 0.861072 2.105263 258.32169
1 Event 01 0.859609 2.383901 257.88261
2 Event 01 0.874982 2.092879 262.49463
3 Event 01 0.904507 2.119195 271.35216
4 Event 01 0.926783 2.156347 278.03496
5 Event 01 0.915608 1.883901 274.68249
Observed Volume(f3)
0 631.5789
1 715.1703
2 627.8637
3 635.7585
4 646.9041
5 565.1703