![](/img/trans.png)
[英]Getting all row combinations from a pandas dataframe based on certain column conditions?
[英]Substr certain parts from a column in Pandas DataFrame based on different conditions
我有一個DataFrame,如下所示:
id Name New_Name
100263 Test Index (UHD) Test Index
100264 Test Num Test Num
如您所見,當“我的Name
列中的值包含(
,我只想要該字符串的左側部分,例如: Test Index (UHD)
-> Test Index
;但是,如果字符串不包含(
,我想要整個字符串,例如: Test Num
> Test Num
我有一個想法,我可以遍歷此列中的所有值以進行更改,例如對於第一個值,我的想法是
try:
pos=data.iloc[0,1].index('(')
except:
pos=len(data.iloc[0,1])
New_Name =data.iloc[0,2][:pos]
我不認為它應該這么復雜,所以有什么簡單的方法可以做到這一點?
假設您只有一個括號組件,您可以像這樣簡化調用
data[ 'New_Name' ] = data.Name.apply( lambda s: s.split( '(', 1 )[ 0 ].strip() )
這是一個帶有簡單regex
的解決方案
regex = re.compile(r'.*?(\(.*?\))')
def strip_brackets(x):
result = re.findall(regex, x)
for r in result:
x = x.replace(r, '')
return ' '.join(x.split())
df = pandas.DataFrame({'Name' : ['Test Index (UHD)', 'Test Num', 'More (foo) complicated (bar) case']})
df['NewName'] = df['Name'].apply(strip_brackets)
print(df)
Name NewName
0 Test Index (UHD) Test Index
1 Test Num Test Num
2 More (foo) complicated (bar) case More complicated case
這是一個可以刪除括號內內容的襯里:
df['New_Name'] = df['Name'].str.replace(r"\(.*\)","")
輸出:
>>df
id Name New_Name
100263 Test Index (UHD) Test Index
100264 Test Num Test Num
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.