【问题标题】:pandas is not summing a numeric column熊猫没有对数字列求和
【发布时间】: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


【解决方案1】:

尝试使用pd.to_numeric

例如:

pp = pd.read_excel('pp.xlsx')
print(pd.to_numeric(pp['Fee'], errors='coerce').dropna().sum())

【讨论】:

  • 顺便说一下,我可以用 pp['Fee'].sum() 得到一个总和:-105.47000000000001。
  • pd.to_numeric(pp['Fee'], errors='coerce').dropna().sum() 产生 -105.47,但 pp.sum() 仍然不打印费用列,这是我最初的问题。
【解决方案2】:

这里的问题是费用列不是数字。因此,您需要将其转换为数字字段,将更新后的字段保存在现有数据框中,然后计算总和。

那就是:

df = df.assign(Fee=pd.to_numeric(df['Fee'], errors='coerce'))
print(df.sum())

【讨论】:

    【解决方案3】:

    经过快速分析,据我所知,您正在用整数替换字符串,'Fee' 列的值可能是浮点数和整数的混合,这意味着该列的 dtypeobject。当您执行pp.sum(numeric_only=True) 时,由于条件numeric_only,它会忽略对象列。将您的列转换为float64,如pp['Fee'] = pd.to_numeric(pp['Fee']),它应该适合您。

    第二次发生的原因是因为excel为你做了数据转换,当你读取它时,它是numeric数据类型。

    【讨论】:

    • could be a mix of both of float and integer which means the dtype of that column is an object 这是错误的,dtype 应该是“float”
    • df1 = pd.DataFrame({ 'A':list('abcdef'), 'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,0], 'E':[5,3,6,9,2,4], 'F':list('aaabbb') }) df1.loc[2,'B'] = 'a' df1.loc[3,'B'] = 0.00 df1['B'].dtype for i in range(df1.shape[0]): if isinstance(df1.loc[i, 'B'], str): df1.loc[i, 'B'] = 0.00 df1['B'].dtype 这应该告诉你故事。我很抱歉这里的缩进。
    • @PaulH 可以看问题下的评论。
    • 我添加了pd.to_numeric(pp['Fee']),但没有任何区别。顺便说一句,我可以用pp['Fee'].sum()得到一个和:-105.47000000000001。
    • 因为没有必要首先循环遍历列的所有元素并将那些字符串元素替换为 0.00。
    【解决方案4】:

    回复的每个人都应该因为告诉我 pd.to_numeric 的事而获得部分功劳。但他们都少了一件。光说pd.to_numeric(pp['Fee'] 是不够的。这将返回转换为数字的列,但 不会 更新原始 DataFrame,所以当我执行pp.sum() 时,pp 中的任何内容都没有被修改。你需要:

    pp['Fee'] = pd.to_numeric(pp['Fee'])
    pp.sum()
    

    【讨论】:

      猜你喜欢
      • 2021-01-28
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 2016-11-23
      相关资源
      最近更新 更多