[英]How to iterate over unique values in pandas and count frequency of associated values
[英]iterate over rows in pandas and count unique hashtags
我有一個包含數千條推文的csv文件。 可以說數據如下:
Tweet_id hashtags_in_the_tweet
Tweet_1 [trump, clinton]
Tweet_2 [trump, sanders]
Tweet_3 [politics, news]
Tweet_4 [news, trump]
Tweet_5 [flower, day]
Tweet_6 [trump, impeach]
如您所見,數據包含tweet_id和每個tweet中的主題標簽。 我想要做的是轉到所有行,最后給我類似值計數的內容:
Hashtag count
trump 4
news 2
clinton 1
sanders 1
politics 1
flower 1
obama 1
impeach 1
考慮到csv文件包含一百萬行(一百萬條推文),什么是最好的方法?
Counter
+ chain
熊貓方法不適用於一系列列表。 不存在矢量化方法。 一種方法是使用標准庫中的collections.Counter
:
from collections import Counter
from itertools import chain
c = Counter(chain.from_iterable(df['hashtags_in_the_tweet'].values.tolist()))
res = pd.DataFrame(c.most_common())\
.set_axis(['Hashtag', 'count'], axis=1, inplace=False)
print(res)
Hashtag count
0 trump 4
1 news 2
2 clinton 1
3 sanders 1
4 politics 1
5 flower 1
6 day 1
7 impeach 1
設定
df = pd.DataFrame({'Tweet_id': [f'Tweet_{i}' for i in range(1, 7)],
'hashtags_in_the_tweet': [['trump', 'clinton'], ['trump', 'sanders'], ['politics', 'news'],
['news', 'trump'], ['flower', 'day'], ['trump', 'impeach']]})
print(df)
Tweet_id hashtags_in_the_tweet
0 Tweet_1 [trump, clinton]
1 Tweet_2 [trump, sanders]
2 Tweet_3 [politics, news]
3 Tweet_4 [news, trump]
4 Tweet_5 [flower, day]
5 Tweet_6 [trump, impeach]
一種使用np.hstack
並轉換為pd.Series
然后使用value_counts
。
import numpy as np
df = pd.Series(np.hstack(df['hashtags_in_the_tweet'])).value_counts().to_frame('count')
df = df.rename_axis('Hashtag').reset_index()
print (df)
Hashtag count
0 trump 4
1 news 2
2 sanders 1
3 impeach 1
4 clinton 1
5 flower 1
6 politics 1
7 day 1
使用np.unique
v,c=np.unique(np.concatenate(df.hashtags_in_the_tweet.values),return_counts=True)
#pd.DataFrame({'Hashtag':v,'Count':c})
甚至問題看起來都不一樣,但仍然是相關的嵌套問題
unnesting(df,['hashtags_in_the_tweet'])['hashtags_in_the_tweet'].value_counts()
聽起來像您想要的是collections.Counter
之類的東西,您可能會這樣使用...
from collections import Counter
from functools import reduce
import operator
import pandas as pd
fold = lambda f, acc, xs: reduce(f, xs, acc)
df = pd.DataFrame({'Tweet_id': ['Tweet_%s'%i for i in range(1, 7)],
'hashtags':[['t', 'c'], ['t', 's'],
['p','n'], ['n', 't'],
['f', 'd'], ['t', 'i', 'c']]})
fold(operator.add, Counter(), [Counter(x) for x in df.hashtags.values])
這給你,
Counter({'c': 2, 'd': 1, 'f': 1, 'i': 1, 'n': 2, 'p': 1, 's': 1, 't': 4})
編輯:我認為jpp的答案會快很多。 如果時間確實是一個約束,那么我將避免首先將數據讀取到DataFrame
中。 我不知道原始的csv
文件是什么樣子,但是按行將其作為文本文件讀取,忽略第一個標記並將其余的內容輸入到Counter
可能最終會快很多。
因此,以上所有答案都是有幫助的,但實際上沒有用! 我的數據存在的問題是:1)對於某些推文提交的'hashtags'
的值是nan
或[]
。 2)數據幀中'hashtags'
字段的值是一個字符串! 以上答案假定主題標簽的值是主題標簽列表,例如['trump', 'clinton']
,而實際上只是一個str
: '[trump, clinton]'
。 所以我在@jpp的答案中添加了幾行:
#deleting rows with nan or '[]' values for in column hashtags
df = df[df.hashtags != '[]']
df.dropna(subset=['hashtags'], inplace=True)
#changing each hashtag from str to list
df.hashtags = df.hashtags.str.strip('[')
df.hashtags = df.hashtags.str.strip(']')
df.hashtags = df.hashtags.str.split(', ')
from collections import Counter
from itertools import chain
c = Counter(chain.from_iterable(df['hashtags'].values.tolist()))
res = pd.DataFrame(c.most_common())\
.set_axis(['Hashtag', 'count'], axis=1, inplace=False)
print(res)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.