我有一個看起來像這樣的資料框:
df = pd.DataFrame({
'name': ['John','William', 'Nancy', 'Susan', 'Robert', 'Lucy', 'Blake', 'Sally', 'Bruce'],
'injury': ['right hand broken', 'lacerated left foot', 'foot broken', 'right foot fractured', '', 'sprained finger', 'chest pain', 'swelling in arm', 'laceration to arms, hands, and foot']
})
name injury
0 John right hand broken
1 William lacerated left foot
2 Nancy foot broken
3 Susan right foot fractured
4 Robert
5 Lucy sprained finger
6 Blake chest pain
7 Sally swelling in arm
8 Bruce lacerations to arm, hands, and foot <-- this is a weird case, since there are multiple body parts
值得注意的是,該列中的某些值injury是空白的。
我想只用受影響的 body partinjury替換列中的值。在我的情況下,那將是手、腳、手指和胸部、手臂。還有幾十個……這是一個小例子。
所需的資料框如下所示:
name injury
0 John hand
1 William foot
2 Nancy foot
3 Susan foot
4 Robert
5 Lucy finger
6 Blake chest
7 Sally arm
8 Bruce arm, hand, foot
我可以做這樣的事情:
df.loc[df['injury'].str.contains('hand'), 'injury'] = 'hand'
df.loc[df['injury'].str.contains('foot'), 'injury'] = 'foot'
df.loc[df['injury'].str.contains('finger'), 'injury'] = 'finger'
df.loc[df['injury'].str.contains('chest'), 'injury'] = 'chest'
df.loc[df['injury'].str.contains('arm'), 'injury'] = 'arm'
但是,這可能不是最優雅的方式。
有沒有更優雅的方法來做到這一點?(例如使用字典)
(對于最后一個有多個身體部位的案例的任何建議將不勝感激)
謝謝!
uj5u.com熱心網友回復:
獲取字串列上正則運算式的第一個匹配項的標準方法是使用.extract(),請參閱pandas 快速入門 10 分鐘:使用文本資料。
df['injury'].str.extract('(arm|chest|finger|foot|hand)', expand=False)
0 hand
1 foot
2 foot
3 foot
4 NaN
5 finger
6 chest
7 arm
8 arm
Name: injury, dtype: object
注意第 4 行回傳 NaN 而不是 '' (但應用.fillna('')到結果很簡單)。更重要的是,在第 8 行中,我們將只回傳第一個匹配項,而不是所有匹配項。您需要決定如何處理這個問題。看.extractall()
uj5u.com熱心網友回復:
我認為您應該維護一個文本串列,并使用應用功能:
body_parts = ['hand', 'foot', 'finger', 'chest', 'arm']
def test(value):
body_text = []
for body_part in body_parts:
if body_part in value:
body_text.append(body_part)
if body_text:
return ', '.join(body_text)
return value
df['injury'] = df['injury'].apply(test)
回傳:
name injury
0 John hand
1 William foot
2 Nancy foot
3 Susan foot
4 Robert
5 Lucy finger
6 Blake chest
7 Sally arm
8 Bruce hand, foot, arm
uj5u.com熱心網友回復:
selected_words = ["hand", "foot", "finger", "chest", "arms", "arm", "hands"]
df["injury"] = (
df["injury"]
.str.replace(",", "")
.str.split(" ", expand=False)
.apply(lambda x: ", ".join(set([i for i in x if i in selected_words])))
)
print(df)
name injury
0 John hand
1 William foot
2 Nancy foot
3 Susan foot
4 Robert
5 Lucy finger
6 Blake chest
7 Sally arm
8 Bruce arms, foot, hands
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/525431.html
標籤:Python熊猫
上一篇:將特定資料框列中的值分隔到某行
下一篇:獲取列中特定單詞之后的第一個單詞
