【问题标题】:Pandas Pivot with Strings- ValueError: Index contains duplicate entries, cannot reshapePandas Pivot with Strings-ValueError:索引包含重复条目,无法重塑
【发布时间】:2018-05-31 05:24:38
【问题描述】:

给定这个数据框:

import pandas as pd
df=pd.DataFrame({'Field':['a','b','a','b'],'Value':['aa','bb','cc','dd'],
'indexer':[0,0,1,1]})

df
  Field Value  indexer
0     a    aa        0
1     b    bb        0
2     a    cc        1
3     b    dd        1

我想生成这样的数据框:

indexer   a   b
0         aa  bb
1         cc  dd

当值字段为数字时,我已经看到了有关如何实现此目的的答案,但我似乎无法使用字符串数据。

我已经尝试过 df.groupby('indexer') 但似乎无法显示它或将其放入数据框中。我已经找到了这些的答案,但它们采用浮点或整数值。

提前致谢!

【问题讨论】:

    标签: python pandas group-by pivot


    【解决方案1】:

    你应该使用crosstab

    例子:

    pd.crosstab(index=df.indexer, columns=df.field, aggfunc=lambda v:v)
    

    【讨论】:

      【解决方案2】:

      存在问题,您的真实数据包含 indexerField 成对重复,因此需要一些聚合函数,例如 ', '.join,因为使用 strings:

      df = df.groupby(['indexer', 'Field'])['Value'].apply(', '.join).unstack()
      print (df)
      Field     a   b
      indexer        
      0        aa  bb
      1        cc  dd
      

      或者:

      df = df.pivot_table(index='indexer', columns='Field', values='Value', aggfunc=','.join)
      

      【讨论】:

      • 谢谢:-),我没有注意到需要加入,当我看到你的回答时,谢谢我的朋友:-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2021-12-22
      相关资源
      最近更新 更多