我試過四處搜索,找不到一個簡單的方法來做到這一點,所以我希望你的專業知識可以提供幫助。Python Pandas使用另一列刪除子字符串
我有兩列
import numpy as np
import pandas as pd
pd.options.display.width = 1000
testing = pd.DataFrame({'NAME':[
'FIRST', np.nan, 'NAME2', 'NAME3',
'NAME4', 'NAME5', 'NAME6'], 'FULL_NAME':['FIRST LAST', np.nan, 'FIRST LAST', 'FIRST NAME3', 'FIRST NAME4 LAST', 'ANOTHER NAME', 'LAST NAME']})
這給了我熊貓數據幀
FULL_NAME NAME
0 FIRST LAST FIRST
1 NaN NaN
2 FIRST LAST NAME2
3 FIRST NAME3 NAME3
4 FIRST NAME4 LAST NAME4
5 ANOTHER NAME NAME5
6 LAST NAME NAME6
什麼,我想要做的就是從「名稱」列中取值,然後刪除如果它在那裏,則從'完整名稱'列。所以函數將返回
FULL_NAME NAME NEW
0 FIRST LAST FIRST LAST
1 NaN NaN NaN
2 FIRST LAST NAME2 FIRST LAST
3 FIRST NAME3 NAME3 FIRST
4 FIRST NAME4 LAST NAME4 FIRST LAST
5 ANOTHER NAME NAME5 ANOTHER NAME
6 LAST NAME NAME6 LAST NAME
到目前爲止,我已經定義了一個函數,並使用apply方法。儘管我的大數據集運行速度很慢,但我希望有一種更有效的方法來實現它。謝謝!
def address_remove(x):
try:
newADDR1 = re.sub(x['NAME'], '', x[-1])
newADDR1 = newADDR1.rstrip()
newADDR1 = newADDR1.lstrip()
return newADDR1
except:
return x[-1]
太棒了!我試圖想出第二個解決方案,但第三個解決方案更好!你介意告訴我「zip」命令在做什麼? – Link
很高興工作! 'zip'需要多次迭代,並從原始迭代中返回聚合的迭代器。用更多的術語來說,它允許你同時循環兩個或多個迭代。 https://docs.python.org/3/library/functions.html#zip – johnchase