簡體   English   中英

Python:計數列 dataframe 中屬於列表的字符串

[英]Python : count string in column dataframe that belong to a list

我花了一天時間試圖解決我的問題...

我有一個從 CSV 文件導入的 DataFrame。 這里有一個例子:

df=pd.DataFrame(['{"choices": ["rougeur", "hematome","oedeme","ecoul","necrose"]}','ecoul','necrose','','oedeme'])

我有我可能的標簽列表:

label_sl=['rougeur', 'hematome', 'oedeme','ecoul','extra','necrose']

我想創建一個新的 dataframe ,它返回:

rougeur hematome oedeme ecoul extra necrose
1 1 1 1 0 1
1 0 0 0 0 0
0 0 0 0 0 1
0 0 0 0 0 0
0 0 1 0 0 0

我找不到解決方案...如果您有想法...

謝謝,

如果包括字典在內的所有值實際上都是字符串,則應該可以:

(df[0].str.replace(r'[\[\]{}"]','',regex=True)
.str.strip()
.str.split('[, ]')
.explode()
.str.get_dummies()
.groupby(level=0).sum()
.reindex(label_sl,axis=1)
.fillna(0)
.astype(int))

Output:

   rougeur  hematome  oedeme  ecoul  extra  necrose
0        1         1       1      1      0        1
1        0         0       0      1      0        0
2        0         0       0      0      0        1
3        0         0       0      0      0        0
4        0         0       1      0      0        0

正則表達式\bsomething\bsomething內容提取為單獨的單詞。 我們可以這樣使用它:

for x in label_sl:
    df[x] = df.iloc[:,0].str.contains("\\b" + x + "\\b").astype(int)

在哪里

label_sl=['rougeur', 'hematome', 'oedeme','ecoul','extra','necrose']
df=pd.DataFrame(['{"choices": ["rougeur", "hematome","oedeme","ecoul","necrose"]}','ecoul','necrose','','oedeme'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM