简体   繁体   English

大熊猫数据框中的列到行

[英]Column to row in pandas dataframe

I would like to use a couple of columns as row ID while taking count of grouping based on Time.我想使用几列作为行 ID,同时根据时间计算分组。 Look at below illustration:看下图:

X Y Z Time
0 1 2  10
0 2 3  10
1 0 2  15
1 0 0  23

Transforms into this:变成这样:

Category Count Time
   X       0    10
   X       1    15
   X       1    23
   Y       3    10
   Y       0    15
   Y       0    23
   Z       5    10
   Z       2    15
   Z       0    23

What is happening is that X occur 0 times for the time 10 but 1 time for 15 and 23 .发生的事情是X在时间10出现了 0 次,但在15 和 23出现了 1 次。
Y occur 3 times at 10 'clock but none at 15 and 23 . Y10 点出现 3 次,但在15 点和 23 点没有出现。 etc.等等。

I think you need melt with groupby aggregating sum and last sort_values by column Category :我认为你需要meltgroupby聚合sum与去年sort_valuesCategory

print pd.melt(df, id_vars='Time', var_name='Category', value_name='Count')
        .groupby(['Time','Category']).sum().reset_index().sort_values('Category')
   Time Category  Count
0    10        X      0
3    15        X      1
6    23        X      1
1    10        Y      3
4    15        Y      0
7    23        Y      0
2    10        Z      5
5    15        Z      2
8    23        Z      0

Another solution with stack : stack另一个解决方案:

df1 = df.set_index('Time')
        .stack()
        .groupby(level=[0,1])
        .sum()
        .reset_index()
        .sort_values('level_1')

df1.columns = ['Time','Category','Count']
df1 = df1[['Category','Count','Time']]
print df1
  Category  Count  Time
0        X      0    10
3        X      1    15
6        X      1    23
1        Y      3    10
4        Y      0    15
7        Y      0    23
2        Z      5    10
5        Z      2    15
8        Z      0    23

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM