看来你需要通过iloc
与where
和sum
选择:
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
对于lambda
功能python
太适用于此。
在大熊猫拉姆达:按行.apply(axis=0)
#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()
:
#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
的。凡差异条款是我需要的。我不明白lambda语法 - 你能指点我一些好的资源吗?谢谢。 – bincob
lambda在熊猫 - 我找不到一些不错的资源。 :( – jezrael
我尝试用lambda函数添加一些示例,我希望它有帮助。 – jezrael