給定一個資料框,我想獲取每行的非零值,然后找到絕對值的最小值。我想要一個用戶定義的函式來為我做這件事。另外,我不想使用任何 for 回圈,因為資料很大。
我的嘗試
np.random.seed(5)
data = np.random.randn(16)
mask = np.random.permutation(16)[:6]
data[mask] = 0
df = pd.DataFrame(data.reshape(4,4))
0 1 2 3
0 0.441227 -0.330870 2.430771 0.000000
1 0.000000 1.582481 -0.909232 -0.591637
2 0.000000 -0.329870 -1.192765 0.000000
3 0.000000 0.603472 0.000000 -0.700179
def udf(x):
if x != 0:
x_min = x.abs().min()
return x_min
df.apply(udf, axis=1)
我明白了ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
問題 我該如何解決上述問題?
期望的答案如下:
0.330870
0.591637
0.329870
0.603472
uj5u.com熱心網友回復:
您可以x.ne(0)
用作布爾索引來過濾行
res = df.apply(lambda x: x[x.ne(0)].abs().min(), axis=1)
print(res)
0 0.330870
1 0.591637
2 0.329870
3 0.603472
dtype: float64
或使用min(axis=1)
res = df[df.ne(0)].abs().min(axis=1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/486557.html
上一篇:在if條件下考慮星期六