[英]How to add a new column to dataframe based on conditions on another column
[英]how to add value to a new column to a dataframe based on the match of another dataframe?
我有兩個大 excel 文件的兩個數據框。 The dataframe 1 is always smaller than dataframe 2. The elements of dataframe 1 are unique while in dataframe there can be many elements repeated by ID and with the same code.
我正在嘗試向我的 dataframe 1 添加一個新列,新列是 dataframe 2 的“代碼”(如果兩個數據幀的 ID 匹配,則添加該值)。
我設法用兩個嵌套的 for 循環解決了這個問題,但是這個過程太慢了。 是否有替代方法來添加新列?
以下數據框非常小,只是為了說明示例,實際上我有大量數據和大量列。
import pandas as pd
details_1 = {'ID':['ID01', 'ID02', 'ID03', 'ID04', 'ID05'],
'Qty': [1,2,3,4,5]}
details_2 = {'ID':['IDA01' ,'ID03', 'ID01','ID02','IDA02','IDX12' 'IDA03', 'IDA04', 'IDA05', 'ID04', 'ID05'],
'code': ['ab','yz','acv','abc','efs','xw2','fgt','axf','ard','afd','x01']
}
df1 = pd.Datafrme(details_1, columns = ['ID', 'Qty'])
df2 = pd.Datafrme(details_2, columns = ['ID', 'code'])
output: print(df3)
ID Qty new_code
0 ID01 1 acv
1 ID02 2 abc
2 ID03 3 yz
3 ID04 4 afd
4 ID05 5 x01
您可以使用.isin
方法:
df3 = df1.set_index('ID')
df3['new_code'] = df2.loc[df2['ID'].isin(df1['ID'])].set_index('ID')
df3.reset_index(inplace=True)
Output:
ID Qty new_code
0 ID01 1 acv
1 ID02 2 abc
2 ID03 3 yz
3 ID04 4 afd
4 ID05 5 x01
請改用合並方法。
這是示例代碼。
df3 = pd.merge(df1, df2, on = "ID")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.