【问题标题】:Is there a short way to count dictionaries values in pandas column?有没有一种简单的方法来计算熊猫列中的字典值?
【发布时间】:2019-08-16 04:55:44
【问题描述】:

我正在尝试计算字典中的值出现在包含词干文本的数据框列中的次数。

我用值列了一个列表,然后应用在计数器函数中计算每行中的每个值

dictionary = {'c-1' : ['x', 'y', 'z'], 'c-2' : ['a', 'b']}

words_list = list()
for key in dictionary.keys():
    words_list.append(dictionary[key])
test = [val for sublist in words_list for val in sublist]

from collections import Counter
text['Counter'] = text['Text'].apply(lambda x: Counter([word for word in x if word in test]))

text = {'text': ['some text', some text'], 'Counter': [Counter({a = 1, x = 2}), Counter({b = 2, y = 4, z = 3})]}

我想显示一列,其中包含每行的结果。也许我选择了一种大的方式来做到这一点。我认为这是直接在字典中工作的直接方式,但我不知道具体如何。

【问题讨论】:

  • 请提供示例数据和您的预期输出。
  • 对于每个字典键,你可以做类似text['Text'].str.count(r'x|y|z')

标签: python pandas dictionary counter


【解决方案1】:

IIUC,使用collections.Counteritertools.chain

from itertools import chain
from collections import Counter

d = {'c-1' : ['x', 'y', 'z'], 'c-2' : ['a', 'b']}
s = pd.Series(['abc', 'xyz', 'abda'])
new_s = s.str.findall('|'.join(chain(*d.values()))).apply(Counter)
print(new_s)

输出:

0            {'b': 1, 'a': 1}
1    {'z': 1, 'x': 1, 'y': 1}
2            {'b': 1, 'a': 2}
dtype: object

【讨论】:

  • “|”是什么意思?
  • 这是一个正则表达式中的or 表达式。查找字典值中的任何字符。
  • 好吧。但是当我运行该行时,Python 会返回我:TypeError: 'float' object is not iterable
  • 似乎text['Text'] 包含float。在这种情况下,列表理解(你的做法)将是最好的选择。
  • 如果 text['Text'] 只是文本,为什么会浮动?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
相关资源
最近更新 更多