【问题标题】:Python pandas create additional dataframe columns by grouping on existing columnPython pandas 通过对现有列进行分组来创建其他数据框列
【发布时间】:2015-09-19 02:55:57
【问题描述】:

尝试从现有列的内容创建新的数据框列。用一个例子更容易解释。我想转换这个:

.	Yr	Month	Class	Cost
1	2015	1	L	19.2361
2	2015	1	M	29.4723
3	2015	1	S	48.5980
4	2015	1	T	169.7630
5	2015	2	L	19.1506
6	2015	2	M	30.0886
7	2015	2	S	49.3765
8	2015	2	T	167.0000
9	2015	3	L	19.3465
10	2015	3	M	29.1991
11	2015	3	S	46.2580
12	2015	3	T	157.7916
13	2015	4	L	18.3165
14	2015	4	M	28.2314
15	2015	4	S	44.5844
16	2015	4	T	162.3241
17	2015	5	L	17.4556
18	2015	5	M	27.0434
19	2015	5	S	42.8841
20	2015	5	T	159.3457
21	2015	6	L	16.5343
22	2015	6	M	24.9853
23	2015	6	S	40.5612
24	2015	6	T	153.4902

...进入以下,以便我可以绘制 4 条单独的线 [L、M、S、T]:

.	 Yr	  Month	   L	   M	   S	   T
1	2015	1	19.2361	29.4723	48.5980	169.7630
2	2015	2	19.1506	30.0886	49.3765	167.0000
3	2015	3	19.3465	29.1991	46.2580	157.7916
4	2015	4	18.3165	28.2314	44.5844	162.3241
5	2015	5	17.4556	27.0434	42.8841	159.3457
6	2015	6	16.5343	24.9853	40.5612	153.4902

通过过滤“类”列上的数据框...然后 3 个单独的合并,我能够以一种非常笨拙的方式完成它。

list_class = ['L', 'M', 'S', 'T']
year = 'Yr'
month = 'Month'
df_class = pd.DataFrame()
df_class1 = pd.DataFrame()
df_class2 = pd.DataFrame()
df_class1 = merge(df[[month, year, 'Class','Cost']][df['Class']==list_class[0]], df[[month, year, 'Class','Cost']][df['Class']==list_class[1]], \
            left_on=[month, year], right_on=[month, year])
df_class2 = merge(df[[month, year, 'Class','Cost']][df['Class']==list_class[2]], df[[month, year, 'Class','Cost']][df['Class']==list_class[3]], \
            left_on=[month, year], right_on=[month, year])
df_class = merge(df_class1, df_class2, left_on=[month, year], right_on=[month, year]).groupby([year, month]).mean().plot(figsize(15,8))

必须有更有效的方法。感觉应该用 groupby 来完成,但我无法确定。

【问题讨论】:

    标签: python pandas filter merge group-by


    【解决方案1】:

    您可以先将df 转换为多级索引类型,然后unstack 级别Class 将为您提供所需的内容。假设 df 是您帖子开头显示的原始数据框。

    df.set_index(['Yr', 'Month', 'Class'])['Cost'].unstack('Class')
    
    Out[29]: 
    Class             L        M        S         T
    Yr   Month                                     
    2015 1      19.2361  29.4723  48.5980  169.7630
         2      19.1506  30.0886  49.3765  167.0000
         3      19.3465  29.1991  46.2580  157.7916
         4      18.3165  28.2314  44.5844  162.3241
         5      17.4556  27.0434  42.8841  159.3457
         6      16.5343  24.9853  40.5612  153.4902
    

    【讨论】:

    • 建勋 - 完美!谢谢你,很抱歉没有提出挑战。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2021-11-25
    • 2020-06-20
    • 2019-06-28
    • 1970-01-01
    • 2021-12-11
    • 2021-08-27
    相关资源
    最近更新 更多