【发布时间】:2021-10-01 19:19:24
【问题描述】:
是的,我查过其他问题,但我仍然无法正确回答。
我有一个多列的 df,像这样
id, hashtag
1234, ['hash1', 'hash2', 'hash3']
1254, [hash1']
1777, ['hash5']
我希望输出中的每个主题标签都有一行,然后将相同的标签分组以便获得它们的频率,例如:
hashtag, count
hash1, 2
hash2, 1
hash3, 1
hash5, 1
但我得到的输出计数错误。这是我的代码:
hashtags_df = df['hashtags'].value_counts().fillna(0).rename_axis('hashtags').reset_index(name='counts')
hashtags_df = df['hashtags'].reset_index(name='index')
hashtags_df['hashtags'] = hashtags_df['hashtags'].apply(lambda x: x.replace('[','').replace(']','')) #doing it because it seems like they're not lists. I'm using twint to extract tweets by the way
hashtags_df['hashtags'] = hashtags_df['hashtags'].astype('string') #the dtype otherwise is an obj
hashtags_df.nunique().sum()
new_df = pd.DataFrame(hashtags_df.hashtags.str.split(',').tolist(), index=hashtags_df.counts).stack()
new_df = new_df.reset_index([0, 'counts'])
new_df.columns =['counts', 'hashtags']
new_df = new_df['hashtags'].value_counts().rename_axis('hashtags').reset_index(name="counts")
print(new_df)
我多次修改代码,现在它搞砸了。感觉解决方案很简单,但我找不到。我该怎么办?
【问题讨论】:
-
这可能以前被问过。如果您的列值看起来不是真正的列表而是字符串,可以尝试
from ast import literal_eval; df.hashtag.apply(literal_eval).explode().value_counts()首先将它们转换为列表。
标签: python python-3.x pandas twitter