![](/img/trans.png)
[英]Create new column using str.contains and based on if-else condition
[英]Create a new column using str.contains and where the condition fails, set it to null (NaN)
我試圖在我的pandas數據框中創建一個新列,但是如果另一個列包含某個字符串,則只能使用一個值。
我的數據框看起來像這樣:
raw val1 val2
0 Vendor Invoice Numbe Inv Date
1 Vendor: Company Name 1 123 456
2 13445 07708-20-2019 US 432 676
3 79935 19028808-15-2019 US 444 234
4 Vendor: company Name 2 234 234
我正在嘗試創建一個新列, vendor
將數據框轉換為:
raw val1 val2 vendor
0 Vendor Invoice Numbe Inv Date Vendor Invoice Numbe Inv Date
1 Vendor: Company Name 1 123 456 Vendor: Company Name 1
2 13445 07708-20-2019 US 432 676 NaN
3 79935 19028808-15-2019 US 444 234 NaN
4 Vendor: company Name 2 234 234 company Name 2
5 Vendor: company Name 2 928 528 company Name 2
但是,只要我嘗試
df['vendor'] = df.loc[df['raw'].str.contains('Vendor', na=False), 'raw']
我得到錯誤
ValueError:無法從重復的軸重新索引
我知道索引4和索引5對公司來說具有相同的價值,但是我在做錯什么以及如何將新列添加到數據框中?
問題是df.loc[df['raw'].str.contains('Vendor', na=False), 'raw']
與df
長度不同。
您可以嘗試np.where
,它通過大小相同的np.array
分配新列,因此不需要索引對齊。
df['vendor'] = np.where(df['raw'].str.contains('Vendor'), df['raw'], np.NaN)
您可以.extract()
在Vendor:
后面的字符串部分Vendor:
使用正向后面:
df['vendor'] = df['raw'].str.extract(r'(?<=Vendor:\\s)(.*)')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.