我有一個包含客戶和國家資料的 df。我想計算這些國家,以便找到前 5 個國家,他們將其用作其他地方的過濾器。
這給了我計數
countries = collections.Counter(responses_2021['country'].dropna())
產生這個
[('US', 144), ('CA', 37), ('GB', 15), ('FR', 15), ('AU', 12)]
這給了我前 5 名
countries_top5 = countries.most_common(5)
現在我需要把它轉換成一個更簡單的結構,這樣我就可以做我的過濾器(這里我只是手動輸入它,因為這是我前進的唯一方法哈哈)
options = ['US', 'CA', 'GB', 'FR', 'AU']
rslt_df = df[df['country'].isin(options)]
所以,要從這個
[('US', 144), ('CA', 37), ('GB', 15), ('FR', 15), ('AU', 12)]
對此
['US', 'CA', 'GB', 'FR', 'AU']
我首先嘗試洗掉計數
countries_top5_names = np.delete(countries_top5, 1, 1)
但這會產生
[['US'], ['CA'], ['GB'], ['FR'], ['AU']]
所以現在我想把它弄平,但我不知道怎么做。
更好的方法?
解決方案(感謝下面的@dan04)
countries_top5_names = [x[0] for x in countries_top5]
rslt_df = df[df['country'].isin(countries_top5_names)]
uj5u.com熱心網友回復:
只需獲取[0]每個元組的元素。
>>> data = [('US', 144), ('CA', 37), ('GB', 15), ('FR', 15), ('AU', 12)]
>>> countries = [x[0] for x in data]
>>> countries
['US', 'CA', 'GB', 'FR', 'AU']
uj5u.com熱心網友回復:
您可以嘗試更通用的方法來做到這一點。
data = [('US', 144), ('CA', 37), ('GB', 15), ('FR', 15), ('AU', 12)]
groups = list(zip(*data))
print(groups[0])
print(groups[1])
輸出:(
'US', 'CA', 'GB', 'FR', 'AU')
(144, 37, 15, 15, 12)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436257.html
上一篇:從兩個numpy陣列制作字典
