嗨,我正在使用 pandas 顯示和分析 csv 檔案,一些列是“object dtype”并顯示為串列,我使用“literal_eval”將名為“sdgs”的列的行轉換為串列,我的問題是如何使用'groupby'或任何其他方式來唯一地顯示存盤在此串列中的每個元素的計數,特別是因為這些串列之間有許多共同元素。
df = pd.read_csv("../input/covid19-public-media-dataset/covid19_articles_20220420.csv")
df.dropna(subset=['sdgs'],inplace=True)
df=df[df.astype(str)['sdgs'] != '[]']
df.sdgs = df.sdgs.apply(literal_eval)
df.reset_index(drop=True, inplace=True)
這是一個資料樣本,我的問題是關于最后一列
這是我要計算的元素的示例
謝謝
uj5u.com熱心網友回復:
鑒于此示例資料:
import pandas as pd
df = pd.DataFrame({'domain': ['a', 'a', 'b', 'c'],
'sdgs': [['Just', 'a', 'sentence'], ['another', 'sentence'],
['a', 'word', 'and', 'a', 'word'], ['nothing', 'here']]})
print(df)
domain sdgs
0 a [Just, a, sentence]
1 a [another, sentence]
2 b [a, word, and, a, word]
3 c [nothing, here]
要獲取列中所有串列的字數,sdgs您可以將串列與Series.agg并使用collections.Counter:
import collections
word_counts = collections.Counter(df['sdgs'].agg(sum))
print(word_counts)
Counter({'a': 3, 'sentence': 2, 'word': 2, 'Just': 1, 'another': 1,
'and': 1, 'nothing': 1, 'here': 1})
uj5u.com熱心網友回復:
您可以explode在這樣的串列中使用:
import pandas as pd
from ast import literal_eval
import re
df = pd.DataFrame({'domain': ['a', 'b'], 'sdgs': ["['AaaBbbAndCcc','DddAndEee']","['BbbCccAndDdd']"]})
df
# domain sdgs
# 0 a ['AaaBbbAndCcc','DddAndEee']
# 1 b ['BbbCccAndDdd']
# turn lists into strings, split at capitalized names
df['sdgs']=df.sdgs.apply(lambda x: re.sub( r"([A-Z])", r" \1", ''.join(literal_eval(x))).split())
df
# domain sdgs
# 0 a [Aaa, Bbb, And, Ccc, Ddd, And, Eee]
# 1 b [Bbb, Ccc, And, Ddd]
df.explode('sdgs')
# domain sdgs
# 0 a Aaa
# 0 a Bbb
# 0 a And
# 0 a Ccc
# 0 a Ddd
# 0 a And
# 0 a Eee
# 1 b Bbb
# 1 b Ccc
# 1 b And
# 1 b Ddd
現在您可以像這樣分組:
df.explode('sdgs').groupby(['domain']).count()
# sdgs
# domain
# a 7
# b 4
編輯:您需要一些其他方式來拆分字串,也可能需要洗掉重復值
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/479369.html
標籤:Python 熊猫 CSV 熊猫-groupby 类型
上一篇:拆分csv逗號分隔值
