【问题标题】:Pivot table from a pandas dataframe without an apply function没有应用功能的熊猫数据框的数据透视表
【发布时间】:2015-09-18 11:36:28
【问题描述】:

我有一个看起来像这样的 pandas 数据框:

df = pd.DataFrame({ 'ID' : [2,2,2,2,2,4,4,3,3,3,6] , 'count' : [20,43,45,50,15,65,35,15,15,14,30]})
df
    ID  count
0    2     20
1    2     43 
2    2     45
3    2     50
4    2     15
5    4     65
6    4     35
7    3     15
8    3     15
9    3     14
10   6     30

我想创建一个具有以下输出的数据透视表:

ID    1    2    3    4    5
 2   20   43   45   50   15
 4   65   35    0    0    0
 3   15   15   14    0    0
 6   30    0    0    0    0

我想对数据框使用数据透视函数 (df_pivot = df.pivot(index='ID', columns=..., values='count') 但我缺少列索引列表。我想应用一个df 的 lambda 函数以生成一个缺少列名的附加列,但我有 800M 个 ID,并且对分组数据帧应用函数非常慢。有没有一种你可能知道的快速方法?

【问题讨论】:

  • 那么,你有一些产生列名的函数吗?
  • 嗨,是的,我想使用以下函数: def f(x): x['Index'] = range(len(x)) return x 然后执行以下操作: df.groupby (['ID']).apply(f)

标签: python pandas dataframe


【解决方案1】:

我将为每个组定义一个子索引:

df['subindex'] = df.groupby('ID').cumcount() + 1

然后应用 pivot 方法将新的 subindex 设置为列,并用 0 填充 NaN 值:

d = pd.pivot_table(df,index='ID',columns='subindex',values='count').fillna(0)

这会返回:

subindex   1   2   3   4   5
ID                          
2         20  43  45  50  15
3         15  15  14   0   0
4         65  35   0   0   0
6         30   0   0   0   0

希望对您有所帮助。

【讨论】:

  • 完美!我不知道 cumcount... 我想我没有耐心到达“Groupby”文档页面的底部 95%!
猜你喜欢
  • 1970-01-01
  • 2019-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
相关资源
最近更新 更多