有什么方法可以获取第一个元素并计算出它在熊猫的各列中出现了多少次?

时间:2019-04-09 13:38:32

标签: python pandas

我正在尝试获取多列中的第一个元素,并计算该值出现多少次。

A       B
1,2,3 23,4,5
2     54 
2     2
result
1  1
2  3
54 1
32 1

1 个答案:

答案 0 :(得分:3)

DataFrame.stack用于Series,然后将Series.str.split用于通过索引选择第一个值,如有必要则转换为整数,并由Series.value_counts进行计数,必要时最后排序:

s = df.stack().str.split(',').str[0].astype(int).value_counts().sort_index()
print (s)
1     1
2     3
23    1
54    1
dtype: int64

如果需要2列DataFrame:

df1 = (df.stack()
         .str.split(',')
         .str[0]
         .astype(int)
         .value_counts()
         .sort_index()
         .rename_axis('result')
         .reset_index(name='counts'))
print (df1)
   result  counts
0       1       1
1       2       3
2      23       1
3      54       1