[英]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.