gpt4 book ai didi

Python数据帧: fill text in certain rows if other columns satisfied

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

我有两列。我想根据第一列中的值填充第二列中的文本。

这是我的代码:

df = pd.DataFrame({'value':[100,10,-5,2],'text':['fine','good',np.nan,np.nan]})
df['text'] = np.where(df['value']<5,'bad')

当前输出:

ValueError: either both or neither of x and y should be given

预期输出:

df = 

value text
0 100 fine
1 10 good
2 -5 bad
3 2 bad

我的代码有什么问题?

更新:下面给出的三个答案的时间安排,numpy 占据了主导地位。这是我原来的 df 包含 25 万行:

%timeit df['text'] = np.where(df['value']<5,'bad',df['text'])
18.2 ms ± 1.4 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit df.loc[df['value']<5,'text'] = 'bad'
31.3 ms ± 4.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit df['text'] = df['text'].mask(df['value']<5, 'bad')
22.8 ms ± 602 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

最佳答案

您需要设置条件的其他部分:

df['text'] = np.where(df['value'] < 5, 'bad', df['text'])
print(df)

# Output
value text
0 100 fine
1 10 good
2 -5 bad
3 2 bad

关于Python数据帧: fill text in certain rows if other columns satisfied,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72397109/

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