[英]How to populate a pandas column by conditional lookup of values in other Pandas DataFrames
我试图通过在其他 DataFrames 中查找值来填充 pandas 列,查找 DataFrame 和列由源数据框中列的内容决定。
这是一个使用 3 个 DataFrame 的示例:
来源_df:
类型 | 代码 | 列_x | 描述 |
---|---|---|---|
ID | 123456 | 废话 | |
废话 | 代码345 | ||
CI | Name_of_thing1 | 废话2 | |
抄送 | 65874 | 胡说八道 | |
ID | 987654 | 废话 |
查找1:
ID | CI | col3 | 描述 |
---|---|---|---|
123456 | Name_of_thing1 | 废话 | 事物描述 1 |
987654 | Name_of_other_1 | 废话 | 其他东西的描述 |
查找2:
抄送 | 事业部 | 描述 |
---|---|---|
65874 | 金融 | 说明哈哈哈哈 |
流行音乐45 | 销售量 | 另一个描述 |
如果可能的话,我想避免使用 for 循环和 if 语句的组合迭代源 DF 的行,但使用 for 循环和 if 语句这是我想要实现的(下面的示例代码旨在作为一种伪代码而不是 100% 正确的 python 代码):
for row in source_df:
if source_df['Type'] == 'ID':
source_df['col_new'] = Lookup1[source_df.loc['row']['Code'] == Lookup1['ID']]['description']
else if source_df['Type'] == 'CI':
source_df['col_new'] = Lookup1[source_df.loc['row']['Code'] == Lookup1['CI']]['description']
else if source_df['Type'] == 'CC':
source_df['col_new'] = Lookup2[source_df.loc['row']['Code'] == Lookup2['CC']]['description']
else:
source_df['col_new'] = source_df.loc['row']['Code2']
是否有可能在没有迭代的情况下实现上述目标?
先将concat
与DataFrame.melt
一起使用,然后通过source_df
左连接,如有必要,使用Series.fillna
替换不匹配的值:
df = pd.concat([Lookup1.melt('description', var_name='Type', value_name='Code'),
Lookup2.melt('description', var_name='Type', value_name='Code')])
print (df)
description Type Code
0 Description of thing 1 ID 123456
1 Description of other thing ID 987654
2 Description of thing 1 CI Name_of_thing1
3 Description of other thing CI Name_of_other_1
4 Description of thing 1 col3 blah
5 Description of other thing col3 blah
0 Description blah blah CC 65874
1 Another Description CC pop45
2 Description blah blah BU finance
3 Another Description BU sales
df = source_df.merge(df, how='left', on=['Type','Code'])
df['description'] = df['description'].fillna(df['Description'])
print (df)
Type Code Column_x Description description
0 ID 123456 blah qwaszx Description of thing 1
1 nan nan blah Code345 NaN
2 CI Name_of_thing1 blah2 abc123 Description of thing 1
3 CC 65874 blah blah aaaeft Description blah blah
4 ID 987654 blah ght567 Description of other thing
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.