在df中添加一列,其中包含df中其他列的值计数?

时间:2020-10-23 16:27:51

标签: python python-3.x pandas dataframe pandas-groupby

我在下面有一个df:

Day 
Morning
Day
Night 
Night
Day
Morning
Day
Day 

此df中还有其他列,不仅包含上述列

当我运行以下代码时:

df.groupby('day').count()

它输出一个df,其中包含日列的每个值在df的其他列中出现的次数(其与天列中的每个值相同的计数)

如何创建一个新列,为“天”列的每个值列出相同的计数?

预期输出:

 Day     New_Col
Morning    2
Day        4
Night      2
Night      2
Day        4
Morning    2
Day        4
Day        4

谢谢!

2 个答案:

答案 0 :(得分:1)

如果要向后映射,请使用transform()

df['New_Col'] = df.groupby('Day')['Day'].transform('count')

或者您可以使用map,也可以使用value_counts()

df['New_Col'] = df['Day'].map(df['Day'].value_counts())

输出:

       Day  New_Col
0  Morning        2
1      Day        4
2    Night        2
3    Night        2
4      Day        4
5  Morning        2
6      Day        4
7      Day        4

答案 1 :(得分:1)

使用df.groupby.transform('size')

df['New_Col'] = df.groupby('Day')['Day'].transform('size')