【发布时间】:2019-09-18 12:56:57
【问题描述】:
我已将一个 Excel 电子表格读入 DataFrame,其中包含 Gross、Fee、Net 等列名。当我在生成的 DataFrame 上调用 sum 方法时,我看到它是未对 Fee 列求和,因为该列中有几行包含字符串数据。因此,我首先遍历每一行测试该列以查看它是否包含字符串,如果包含,我将其替换为 0。DataFrame sum 方法仍然不会对 Fee 列求和。然而,当我将生成的 DataFrame 写入新的 Excel 电子表格并将其读回并将 sum 方法应用于生成的 DataFrame 时,它确实对 Fee 列求和。谁能解释一下?这是代码和打印输出:
import pandas as pd
pp = pd.read_excel('pp.xlsx')
# get rid of any strings in column 'Fee':
for i in range(pp.shape[0]):
if isinstance(pp.loc[i, 'Fee'], str):
pp.loc[i, 'Fee'] = 0
pd.to_numeric(pp['Fee']) #added this but it makes no difference
# the Fee column is still not summed:
print(pp.sum(numeric_only=True))
print('\nSecond Spreadsheet\n')
# write out Dataframe: to an Excel spreadheet:
with pd.ExcelWriter('pp2.xlsx') as writer:
pp.to_excel(writer, sheet_name='PP')
# now read the spreadsheet back into another DataFrame:
pp2 = pd.read_excel('pp2.xlsx')
# the Fee column is summed:
print(pp2.sum(numeric_only=True))
打印:
Gross 8677.90
Net 8572.43
Address Status 0.00
Shipping and Handling Amount 0.00
Insurance Amount 0.00
Sales Tax 0.00
etc.
Second Spreadsheet
Unnamed: 0 277885.00
Gross 8677.90
Fee -105.47
Net 8572.43
Address Status 0.00
Shipping and Handling Amount 0.00
Insurance Amount 0.00
Sales Tax 0.00
etc.
【问题讨论】:
-
你能在第一次做
pp.sum(numeric_only=True)之前先做一个pp['Fee'].dtype吗? -
pp['Fee'].dtype -> 对象
-
我的回答对你有意义吗? Pandas 应该固有地将列转换为
float64,但我不知道为什么在这种情况下它不这样做。 -
@Danny “接受”的答案还将列转换为 float64,而
to_numeric(pp['Fee'])似乎没有。
标签: excel python-3.x pandas