gpt4 book ai didi

python - 在 DataFrame 上应用 .value_counts(),并在每个单元格中填充列表

转载 作者:行者123 更新时间:2023-12-01 03:16:56 32 4
gpt4 key购买 nike

我当前正在使用一个数据框,它的每个单元格中都有一个列表类型的列(带有字符串)。我有兴趣对其应用 value.counts() ,就好像所有列表都会连接成一个巨大的列表(尝试这样做,效果不太好)

我拥有的数据结构的玩具示例:

import pandas as pd
df_list = pd.DataFrame({'listcol':[['a','b','c'],['a','b','c']]})
print df_list
listcol
0 [a, b, c]
1 [a, b, c]

我想对其应用value.counts(),如果它是一个大的串联列表,如下所示:

#desired output:
df=pd.DataFrame(['a','b','c','a','b','c'])
df.columns = ['col']
df.col.value_counts() #desired output!
b 2
c 2
a 2

提前致谢!

最佳答案

我认为你需要首先创建扁平化list,然后应用Counter,最后创建Series:

from  itertools import chain
from collections import Counter

print (Counter(chain.from_iterable(df_list['listcol'])))
Counter({'b': 2, 'a': 2, 'c': 2}

s = pd.Series(Counter(chain.from_iterable(df_list['listcol'])))
print (s)
a 2
b 2
c 2
dtype: int64

或者创建系列并使用value_counts :

#for python 2 omit list
s = pd.Series(list(chain.from_iterable(df_list['listcol'])))
print (s)
0 a
1 b
2 c
3 a
4 b
5 c
dtype: object

print (s.value_counts())
c 2
a 2
b 2
dtype: int64

关于python - 在 DataFrame 上应用 .value_counts(),并在每个单元格中填充列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42391605/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com