如何根据另一个 df 的条件填充 pandas df?

问题描述 投票:0回答:1

我正在考虑 2 张桌子:

表1:

国家 年龄 标记
A 25 7
B 45 8

表2:

年龄范围 年龄范围 A国 B国
20 30
40 50

我想要的输出:

年龄范围 年龄范围 A国 B国
20 30 7 NaN
40 50 NaN 8

这是我尝试过的:

for index,row in table2.iterrows():
    table2.loc[index,'Country A'] = table1[(table1['Country']=='A')&
                                           (table1['Age']>=row[0])&
                                           (table1['Age']<=row[1])]['Marks'].values[0]

但这会出现以下错误:

index 0 is out of bounds for axis 0 with size 0

我想我可能已经猜到错误发生在哪里: 每当编译器遇到表 2 中的年龄范围,而表 1 中不存在对应的年龄时。

非常感谢对此问题的任何帮助!提前谢谢您...

pandas dataframe data-manipulation data-filtering
1个回答
0
投票

使用

DataFrame.merge
和通过
df1
 旋转 
DataFrame.pivot
并按
Series.between
过滤值:

out = (df2[['Age Band From','Age Band To']]
            .merge(df1.pivot(index='Age', columns='Country', values='Marks')
                       .add_prefix('Country ').reset_index(), how='cross'))

out = out[out['Age'].between(out['Age Band From'], out['Age Band To'])]
print (out)
   Age Band From  Age Band To  Age  Country A  Country B
0             20           30   25        7.0        NaN
3             40           50   45        NaN        8.0
© www.soinside.com 2019 - 2024. All rights reserved.