gpt4 book ai didi

python-3.x - Pandas 根据另一列分配一列的值

转载 作者:行者123 更新时间:2023-12-04 01:49:31 26 4
gpt4 key购买 nike

给定以下数据框:

import pandas as pd
df = pd.DataFrame(
{'A':[10,20,30,40,50,60],
'B':[1,2,1,4,5,4]
})
df

A B
0 10 1
1 20 2
2 30 1
3 40 4
4 50 5
5 60 4

我希望新列“C”的值等于“A”中的值,其中“B”的相应值小于 3,否则为 0。期望的结果如下:

    A   B  C
0 10 1 10
1 20 2 20
2 30 1 30
3 40 4 0
4 50 5 0
5 60 4 0

提前致谢!

最佳答案

使用np.where :

df['C'] = np.where(df['B'] < 3, df['A'], 0)

>>> df
A B C
0 10 1 10
1 20 2 20
2 30 1 30
3 40 4 0
4 50 5 0
5 60 4 0

关于python-3.x - Pandas 根据另一列分配一列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35068722/

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