![](/img/trans.png)
[英]Generate a new dataframe with boolean column based on comparing other dataframes values
[英]creating a new column in a dataframe based on 4 other dataframes
假設我們有 4 個數據框
df1(35000, 20)
df2(12000, 21)
df3(323, 18)
df4(220, 6)
這是變得棘手的地方:
df4 was created by a merge of df3 and df2 based on 1 column.
It took 3 columns from df3 and 3 columns from df2. (that is why it has 6 cols in total)
我想要的是以下內容:我希望在 df1 中創建一個額外的列,並為在 df1 和 df3 的特定列中具有相同值的行插入特定值。 出於這個原因,我做了以下
df1['new col'] = df1['Name'].isin(df3['Name'])
現在,無論 df1 和 df2 的列名中的值是否相同,我的新列都填充了 True/False 值。 到目前為止一切都很好,但是我想用 df2 中特定列的值填充這個新列。 我嘗試了以下
df1['new col'] = df1['Name'].map({True:df2['Address'],False:'no address inserted'})
但是,它會在該單元格中插入來自 df2 的所有地址值,而不是僅插入所需的 1 值。 有任何想法嗎?
我還嘗試了以下
merged = df2(df4, how='left', left_on='Name',right_on = 'First Name', indicator=True)
df1['Code'] = np.where(merged['_merge'] == 'both', merged['Address'], 'n.a.')
但我收到以下錯誤
Length of values (1210) does not match length of index (35653)
使用how='left'
merge
,然后用fillna
填充缺失值。
merged = df2(df4, how='left', left_on='Name',right_on = 'First Name', indicator=True)
merged[address_column].fillna('n.a.', inplace=True) #address column is the name or list of names of columns that you want the replace the nan's with
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.