Python Pandas Dataframe有条件地添加到负数

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

这里是随机整数数据帧,df:

df = pd.DataFrame(np.random.randint(-10,10,size=(12, 4)), columns=list('ABCD'))

Output:
     A  B  C   D
0   -6  0 -9  -9
1   -7  1 -7  -4
2  -10 -8 -7   7
3   -1 -7 -4   2
4   -1  1  7   5
5    8  7  4 -10
6    1 -1 -6  -6
7   -1  6 -1   8
8   -2  3 -4   5
9   -9 -6  6  -5
10   6  8 -1   2
11   9 -1  1  -5

对于“ D”列中的所有负值,我想在不使用循环且不更改数据帧中任何其他值的情况下加10。

提前感谢!

这里是一个随机整数数据帧,df:df = pd.DataFrame(np.random.randint(-10,10,size =(12,4)),column = list('ABCD'))输出:ABCD 0 -6 0 -9 -9 1 -7 1 -7 -4 2 -10 -8 -7 7 3 ...

python pandas dataframe negative-number
2个回答
0
投票
df.D = df.D+np.where(df.D<0, 10, 0)

0
投票

最佳方法是使用loc:

© www.soinside.com 2019 - 2024. All rights reserved.