我有一個資料框,它由兩列組成,全名和姓氏。有時,姓氏列未正確填寫。在這種情況下,姓氏將作為括號之間的全名列中的最后一個單詞找到。對于發現括號等于括號之間的單詞的情況,我想更新我的姓氏列。
代碼
import pandas as pd
df = pd.DataFrame({
'full':['bob john smith','sam alan (james)','zack joe mac', 'alan (gracie) jacob (arnold)'],
'last': ['ross', '-', 'mac', '-']
})
result_to_be = pd.DataFrame({
'full':['bob john smith','sam alan (james)','zack joe mac', 'alan (gracie) jacob (arnold)'],
'last': ['ross', 'james', 'mac', 'arnold']
})
print(df)
print(result_to_be)
我試圖實作包含函式以用作掩碼,但在檢查它是否包含“)”或“(”字符時,它似乎弄亂了檢查正則運算式
df['full'].str.contains(')')
它顯示的錯誤是
re.error:位置 0 的括號不平衡
uj5u.com熱心網友回復:
您可以使用.str.findall來獲取括號之間的值并df.loc指定 where lastis -:
df.loc[df['last'] == '-', 'last'] = df['full'].str.findall('\((. ?)\)').str[-1]
輸出:
>>> df
full last
0 bob john smith ross
1 sam alan (james) james
2 zack joe mac mac
3 alan (gracie) jacob (arnold) arnold
uj5u.com熱心網友回復:
對于稍微不同的語法,您還可以使用extract
df.loc[df['last'] == '-', 'last'] = df['full'].str.extract('.*\((.*)\)', expand=False)
輸出:
full last
0 bob john smith ross
1 sam alan (james) james
2 zack joe mac mac
3 alan (gracie) jacob (arnold) arnold
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/466206.html
