每行包含整个数据集中特定值的计数的列

时间:2018-12-16 10:47:34

标签: python pandas

我正在尝试创建一个新列,该列将为每行包含整个数据集中特定值的计数。

我有以下数据框:

import pandas as pd
df = pd.DataFrame({'a': [1,2,3,4,5], 'b': [2,3,4,5,6], 'c':['or','ta','fl','or','fl'], 'd':[5,9,1,3,7]})

我想添加一列e,该列为每行计数列c的值出现在数据集中的次数,如下所示:

df = pd.DataFrame({'a': [1,2,3,4,5], 'b': [2,3,4,5,6], 'c':['or','ta','fl','or','fl'], 'd':[5,9,1,3,7], 'e':[2,1,2,2,2]})

   a  b   c  d  
0  1  2  or  5  
1  2  3  ta  9  
2  3  4  fl  1  
3  4  5  or  3  
4  5  6  fl  7  

我尝试遍历整个数据集,但是没有用:

def getSum(c):
return df[df==c].sum()

def createE(df):
for index, row in df.iterrows():
    row['e'] = getSum(row['c'])

return df


   a  b   c  d  e
0  1  2  or  5  2
1  2  3  ta  9  1
2  3  4  fl  1  2
3  4  5  or  3  2
4  5  6  fl  7  2

2 个答案:

答案 0 :(得分:2)

为此使用GroupBy.transform,并为参数'count'使用transform

df['e']=df.groupby('c')['c'].transform('count')

现在:

print(df)

是:

   a  b   c  d  e
0  1  2  or  5  2
1  2  3  ta  9  1
2  3  4  fl  1  2
3  4  5  or  3  2
4  5  6  fl  7  2

答案 1 :(得分:2)

您可以将c列中的每个值映射为其计数。

设置

>>> df = pd.DataFrame({'a': [1,2,3,4,5], 'b': [2,3,4,5,6], 'c':['or','ta','fl','or','fl'], 'd':[5,9,1,3,7]})           
>>> df                                                                                                                 
   a  b   c  d
0  1  2  or  5
1  2  3  ta  9
2  3  4  fl  1
3  4  5  or  3
4  5  6  fl  7

解决方案

>>> df['e'] = df.c.map(df.c.value_counts())                                                                            
>>> df                                                                                                                 
   a  b   c  d  e
0  1  2  or  5  2
1  2  3  ta  9  1
2  3  4  fl  1  2
3  4  5  or  3  2
4  5  6  fl  7  2
相关问题