【问题标题】:The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()DataFrame 的真值是模棱两可的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
【发布时间】:2018-03-28 09:26:03
【问题描述】:

我有一个我正在尝试旋转的 DataFrame。

df

   col_1    col_2   col_3   col_4
    John    Method  4       White
     Tom    Method  29613   White
   Harry    Method  147     White
    John    Method  84      Blue
     Tom    Method  28      Blue
    John    Method  222085  Black
     Tom    Method  159459  Black
   Harry    Method  2204225 Black
    John    Method  600253  Green
     Tom    Method  3156210 Green
   Harry    Method  4343635 Green
   Harry    Method  4343635 Green

预期结果:

newDf

           Black    Blue    Green   White
Harry     2204225          8687270  147
John       222085   84     600253   4
 Tom       159459   28     3156210  29613

我的代码:

newDf = pd.pivot_table(df, values='col_3', index=['col_1'], columns=['col_4'], aggfunc={'col_3' : 'sum'})

列类型如下:

df.dtypes 

col_1     object
col_2     object
col_3     int64
col_4      object
dtype: object

错误:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

有人可以帮我吗?谢谢!

【问题讨论】:

  • 您的错误无法重现,请告诉我们更多细节
  • 您能否使用提供的示例 DF 重现该错误?你的 Pandas 版本是什么?

标签: python pandas dataframe


【解决方案1】:
In [54]: df.pivot_table(values='col_3', index='col_1', columns='col_4', aggfunc='sum', fill_value=0)
Out[54]:
col_4    Black  Blue    Green  White
col_1
Harry  2204225     0  8687270    147
John    222085    84   600253      4
Tom     159459    28  3156210  29613

如果你想用空字符串替换 NaN:

In [55]: df.pivot_table(values='col_3', index='col_1', columns='col_4', aggfunc='sum', fill_value='')
Out[55]:
col_4    Black Blue    Green  White
col_1
Harry  2204225       8687270    147
John    222085   84   600253      4
Tom     159459   28  3156210  29613

但结果包含此类空字符串的列将是string (object) dtype:

In [56]: df.pivot_table(values='col_3', index='col_1', columns='col_4', aggfunc='sum', fill_value='').dtypes
Out[56]:
col_4
Black     int64
Blue     object
Green     int64
White     int64
dtype: object

【讨论】:

    【解决方案2】:

    您已经将字典传递给aggfunc,那么您不需要将列指向value

    pd.pivot_table(df,index=['col_1'], columns=['col_4'], aggfunc={'col_3' : 'sum'})
    Out[564]: 
               col_3                          
    col_4      Black  Blue      Green    White
    col_1                                     
    Harry  2204225.0   NaN  8687270.0    147.0
    John    222085.0  84.0   600253.0      4.0
    Tom     159459.0  28.0  3156210.0  29613.0
    

    【讨论】:

      【解决方案3】:

      在进行数据透视之前,您需要处理缺失值。 df.fillna(0, inplace=True) 会成功的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-12
        • 2021-02-01
        • 1970-01-01
        • 2017-09-23
        • 2019-05-04
        • 1970-01-01
        • 2021-06-02
        • 2016-12-14
        相关资源
        最近更新 更多