Pandas 根据另一个数据框中的匹配列填充新的数据框列
Pandas populate new dataframe column based on matching columns in another dataframe
我有一个df
,其中包含我的主要数据,有一百万rows
。我的主数据也有30个columns
。现在我想在我的 df
中添加另一个名为 category
的列。 category
是 df2
中的 column
,其中包含大约 700 个 rows
和另外两个 columns
,它们将与 [=14] 中的两个 columns
匹配=].
我首先在 df2
和 df
中设置一个 index
来匹配帧,但是 df2
中的一些 index
不匹配不存在于 df
.
df2
中的其余列称为 AUTHOR_NAME
和 CATEGORY
。
df
中的相关列称为 AUTHOR_NAME
。
df
中的某些 AUTHOR_NAME
在 df2
中不存在,反之亦然。
我想要的指令是:当df
中的index
与df2
中的index
匹配并且df
中的title
与title
在 df2
中,将 category
添加到 df
,否则在 category
中添加 NaN。
示例数据:
df2
AUTHOR_NAME CATEGORY
Index
Pub1 author1 main
Pub2 author1 main
Pub3 author1 main
Pub1 author2 sub
Pub3 author2 sub
Pub2 author4 sub
df
AUTHOR_NAME ...n amount of other columns
Index
Pub1 author1
Pub2 author1
Pub1 author2
Pub1 author3
Pub2 author4
expected_result
AUTHOR_NAME CATEGORY ...n amount of other columns
Index
Pub1 author1 main
Pub2 author1 main
Pub1 author2 sub
Pub1 author3 NaN
Pub2 author4 sub
如果我使用 df2.merge(df,left_index=True,right_index=True,how='left', on=['AUTHOR_NAME'])
,我的 df
会比预期的大三倍。
所以我想也许合并是解决这个问题的错误方法。我真正想做的是使用 df2
作为查找 table 然后 return type
值到 df
取决于是否满足某些条件。
def calculate_category(df2, d):
category_row = df2[(df2["Index"] == d["Index"]) & (df2["AUTHOR_NAME"] == d["AUTHOR_NAME"])]
return str(category_row['CATEGORY'].iat[0])
df.apply(lambda d: calculate_category(df2, d), axis=1)
然而,这会抛出一个错误:
IndexError: ('index out of bounds', u'occurred at index 7614')
方法 1:
您可以使用 concat
instead and drop the duplicated values present in both Index
and AUTHOR_NAME
columns combined. After that, use isin
检查成员资格:
df_concat = pd.concat([df2, df]).reset_index().drop_duplicates(['Index', 'AUTHOR_NAME'])
df_concat.set_index('Index', inplace=True)
df_concat[df_concat.index.isin(df.index)]
注:Index
列假定为 DF's
.
的索引列
方法 2:
正确设置索引列后使用join
如图:
df2.set_index(['Index', 'AUTHOR_NAME'], inplace=True)
df.set_index(['Index', 'AUTHOR_NAME'], inplace=True)
df.join(df2).reset_index()
考虑以下数据帧 df
和 df2
df = pd.DataFrame(dict(
AUTHOR_NAME=list('AAABBCCCCDEEFGG'),
title= list('zyxwvutsrqponml')
))
df2 = pd.DataFrame(dict(
AUTHOR_NAME=list('AABCCEGG'),
title =list('zwvtrpml'),
CATEGORY =list('11223344')
))
选项 1
merge
df.merge(df2, how='left')
选项 2
join
cols = ['AUTHOR_NAME', 'title']
df.join(df2.set_index(cols), on=cols)
两种选择都产生
虽然这里的其他答案对所提出的问题给出了非常好的和优雅的解决方案,但我找到了一个资源,既可以以极其优雅的方式回答这个问题,也可以提供一组非常清晰和直接的示例如何完成数据帧的连接/合并,有效地教授 LEFT、RIGHT、INNER 和 OUTER 连接。
Join And Merge Pandas Dataframe
老实说,我觉得这个主题之后的任何进一步寻求者也想检查他的例子...
您可以尝试以下方法。它将合并指定列上的两个数据集作为键。
expected_result = pd.merge(df, df2, on = 'CATEGORY', how = 'left')
我有一个df
,其中包含我的主要数据,有一百万rows
。我的主数据也有30个columns
。现在我想在我的 df
中添加另一个名为 category
的列。 category
是 df2
中的 column
,其中包含大约 700 个 rows
和另外两个 columns
,它们将与 [=14] 中的两个 columns
匹配=].
我首先在 df2
和 df
中设置一个 index
来匹配帧,但是 df2
中的一些 index
不匹配不存在于 df
.
df2
中的其余列称为 AUTHOR_NAME
和 CATEGORY
。
df
中的相关列称为 AUTHOR_NAME
。
df
中的某些 AUTHOR_NAME
在 df2
中不存在,反之亦然。
我想要的指令是:当df
中的index
与df2
中的index
匹配并且df
中的title
与title
在 df2
中,将 category
添加到 df
,否则在 category
中添加 NaN。
示例数据:
df2
AUTHOR_NAME CATEGORY
Index
Pub1 author1 main
Pub2 author1 main
Pub3 author1 main
Pub1 author2 sub
Pub3 author2 sub
Pub2 author4 sub
df
AUTHOR_NAME ...n amount of other columns
Index
Pub1 author1
Pub2 author1
Pub1 author2
Pub1 author3
Pub2 author4
expected_result
AUTHOR_NAME CATEGORY ...n amount of other columns
Index
Pub1 author1 main
Pub2 author1 main
Pub1 author2 sub
Pub1 author3 NaN
Pub2 author4 sub
如果我使用 df2.merge(df,left_index=True,right_index=True,how='left', on=['AUTHOR_NAME'])
,我的 df
会比预期的大三倍。
所以我想也许合并是解决这个问题的错误方法。我真正想做的是使用 df2
作为查找 table 然后 return type
值到 df
取决于是否满足某些条件。
def calculate_category(df2, d):
category_row = df2[(df2["Index"] == d["Index"]) & (df2["AUTHOR_NAME"] == d["AUTHOR_NAME"])]
return str(category_row['CATEGORY'].iat[0])
df.apply(lambda d: calculate_category(df2, d), axis=1)
然而,这会抛出一个错误:
IndexError: ('index out of bounds', u'occurred at index 7614')
方法 1:
您可以使用 concat
instead and drop the duplicated values present in both Index
and AUTHOR_NAME
columns combined. After that, use isin
检查成员资格:
df_concat = pd.concat([df2, df]).reset_index().drop_duplicates(['Index', 'AUTHOR_NAME'])
df_concat.set_index('Index', inplace=True)
df_concat[df_concat.index.isin(df.index)]
注:Index
列假定为 DF's
.
方法 2:
正确设置索引列后使用join
如图:
df2.set_index(['Index', 'AUTHOR_NAME'], inplace=True)
df.set_index(['Index', 'AUTHOR_NAME'], inplace=True)
df.join(df2).reset_index()
考虑以下数据帧 df
和 df2
df = pd.DataFrame(dict(
AUTHOR_NAME=list('AAABBCCCCDEEFGG'),
title= list('zyxwvutsrqponml')
))
df2 = pd.DataFrame(dict(
AUTHOR_NAME=list('AABCCEGG'),
title =list('zwvtrpml'),
CATEGORY =list('11223344')
))
选项 1
merge
df.merge(df2, how='left')
选项 2
join
cols = ['AUTHOR_NAME', 'title']
df.join(df2.set_index(cols), on=cols)
两种选择都产生
虽然这里的其他答案对所提出的问题给出了非常好的和优雅的解决方案,但我找到了一个资源,既可以以极其优雅的方式回答这个问题,也可以提供一组非常清晰和直接的示例如何完成数据帧的连接/合并,有效地教授 LEFT、RIGHT、INNER 和 OUTER 连接。
Join And Merge Pandas Dataframe
老实说,我觉得这个主题之后的任何进一步寻求者也想检查他的例子...
您可以尝试以下方法。它将合并指定列上的两个数据集作为键。
expected_result = pd.merge(df, df2, on = 'CATEGORY', how = 'left')