gpt4 book ai didi

python - 如何根据另一个数据框中的条件在数据框中创建新列?

转载 作者:行者123 更新时间:2023-12-05 01:24:12 25 4
gpt4 key购买 nike

df1:

Variables left right
0 AUM -0.001 28.20
1 AUM 28.20 40.28
2 AUM 40.28 58.27
3 AUM 58.27 80.72
4 AUM 80.72 100.00
0 ABS -88.01 200.72
1 ABS 200.72 480.72
2 ABS 480.72 800.20
0 LS 10000 200000
1 LS 200000 400000
df2:

Pan_no ABS AUM LS
0 AAA 28 30 10001
2 CCC 500 98 390000
1 BBB 250 50 150000
3 DDD 100 60 380000
4 EEE 88 10 378347

条件:

根据df1中的左右值,在df2中新建一列,里面的值该列应该是该特定变量的 df1 索引。

例子:在 df2 中,如果 AUM 值在此范围内 (-0.001 - 28.20),则新列将具有索引值df1 作为新值。即 0

同样,

在 df2 中,如果 ABS 值在此范围内 (200.72 - 480.72),则新列 ABS_BIN 将以 df1 的索引值作为新值。即 1

我试过的是:

binning_vars = ['ABS','AUM','LS']
def f(row):
for i in binning_vars:
for j in df1[df1['Variable'] == i].index:
if df1[i] >= df1['left'] & df1[i] >= df1['right']:
value = j
else:
pass
return value
df2[i,'_bin'] = df1.apply(f, axis=1)

但它会抛出一个错误 TypeError: unsupported operand type(s) for &: 'float' and 'float'。任何帮助将不胜感激。

Expected Output:
with new columns in df2:

Pan_no ABS AUM LS ABS_BIN AUM_BIN LS_BIN
0 AAA 28 30 10001 0 1 0
1 BBB 250 50 150000 1 2 0
2 CCC 500 98 390000 2 4 1
3 DDD 100 60 380000 0 3 1
4 EEE 88 10 378347 0 0 1

最佳答案

你可以使用merge_asof来避免使用apply:

out = df2.merge(
pd.merge_asof((df2.melt(id_vars='Pan_no')
.astype({'value': float})
.sort_values(by='value')
),
df1.reset_index().sort_values(by='left'),
left_by='variable', right_by='Variables',
left_on='value', right_on='left', direction='backward')
.pivot(index='Pan_no', columns='variable', values='index')
.add_suffix('_BIN'),
left_on='Pan_no', right_index=True
)

输出:

  Pan_no  ABS  AUM      LS  ABS_BIN  AUM_BIN  LS_BIN
0 AAA 28 30 10001 0 1 0
2 CCC 500 98 390000 2 4 1
1 BBB 250 50 150000 1 2 0
3 DDD 100 60 380000 0 3 1
4 EEE 88 10 378347 0 0 1

关于python - 如何根据另一个数据框中的条件在数据框中创建新列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71568366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com