gpt4 book ai didi

python - Pandas 数据帧 : Conditionally select columns

转载 作者:行者123 更新时间:2023-12-01 03:14:11 26 4
gpt4 key购买 nike

我有一个 pandas 数据框,如下所示......

   C1  C2   C3     C4
0 -1 -3 3 0.75
1 10 20 30 -0.50

我只想添加每行中值小于零的前两列。例如,我针对上述案例获得的系列如下......

   CR
0 -4
1 0

我知道如何应用下面的其他功能...

df.iloc[:, :-2].abs().sum(axis = 1)

有没有办法使用 lambda 函数?

最佳答案

看来你需要选择ilocwhere总和:

df = df.iloc[:,:2].where(df < 0).sum(axis=1)
print (df)
0 -4.0
1 0.0
dtype: float64

如果需要解决方案 selection by callable :

df = df.iloc[:, lambda df: [0,1]].where(df < 0).sum(axis=1)
print (df)
0 -4.0
1 0.0
dtype: float64

对于 python 中的 lambda 函数也适用于此。

pandas 中的 lambda:

#sample data
np.random.seed(100)
df = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (df)
A B C D E
0 8 8 3 7 7
1 0 4 2 5 2
2 2 2 1 0 8
3 4 0 9 6 2
4 4 1 5 3 4

按行获取差异.apply(axis=0)默认值相同.apply():

#instead function f1 is possible use lambda, if function is simple
print (df.apply(lambda x: x.max() - x.min()))
A 8
B 8
C 8
D 7
E 6
dtype: int64

def f1(x):
#print (x)
return x.max() - x.min()

print (df.apply(f1))
A 8
B 8
C 8
D 7
E 6
dtype: int64

按列获取差异.apply(axis=1)

#instead function f2 is possible use lambda, if function is simple
print (df.apply(lambda x: x.max() - x.min(), axis=1))
0 5
1 5
2 8
3 9
4 4
dtype: int64

def f2(x):
#print (x)
return x.max() - x.min()

print (df.apply(f2, axis=1))
0 5
1 5
2 8
3 9
4 4
dtype: int64

关于python - Pandas 数据帧 : Conditionally select columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42610866/

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