在我的 DataFrame 中,我希望将特定列的值剪裁在 0 到 100 之间。例如,给定以下内容:
a b
0 10 90
1 20 150
2 30 -30
我想得到:
a b c
0 10 90 90
1 20 150 100
2 30 -30 0
我知道在 Pandas 中,某些算术运算是跨列进行的。例如,我可以像这样将 b
列中的每个数字加倍:
>>>df["c"] = df["b"] * 2
>>>df
a b c
0 10 90 180
1 20 150 300
2 30 -30 -60
然而,这不适用于内置函数,如 min
和 max
:
>>>df["c"] = min(100, max(0, df["b"]))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
有什么方法可以高效地完成我想要的吗?
最佳答案
您可以使用 Series.clip
:
df['c'] = df['b'].clip(0,100)
print (df)
a b c
0 10 90 90
1 20 150 100
2 30 -30 0
关于python - Pandas 可以按行执行 min() 和 max() 函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45966493/