假设我有这样的 df
对 st 列使用 python 和 pandas 我想计算 name_x 值,然后从字符串中提取前 3 个关键词。
例如像这样:
有什么办法可以解决这个任务吗?
最佳答案
我会首先使用 groupby() 来连接您显示的字符串,然后使用集合 Counter
,然后使用 most_common
。最后将其分配回数据框。我正在使用 x.lower()
,否则“他”和“他”将被视为不同的词(但如果有意,您可以随时将其删除):
output = df.groupby('st').agg(
name_x_count = pd.NamedAgg('name_x','count'),
string = pd.NamedAgg('string',' '.join))
分组后,我们使用 collections.Counter()
创建列:
output[['top1_word','top2_word','top3_word']] = output['string'].map(lambda x: [x[0] for x in collections.Counter(x.lower().split()).most_common(3)])
output = output.drop(columns='string')
输出:
name_x_count top1_word top2_word top3_word
st
us 2 he with was
us1 2 the and overpass
us2 1 random words in
关于python - 使用 python 和 pandas 按数据框分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74385812/