Pandas可以执行行式min()和max()函数吗?

ste*_*esu 7 python dataframe pandas

在我的DataFrame中,我希望将特定列的值剪切为0到100.例如,给定以下内容:

  a  b
0 10 90
1 20 150
2 30 -30
Run Code Online (Sandbox Code Playgroud)

我想得到:

  a  b   c
0 10 90  90
1 20 150 100
2 30 -30 0
Run Code Online (Sandbox Code Playgroud)

我知道在Pandas中,某些算术运算跨列工作.例如,我可以将列中的每个数字加倍,b如下所示:

>>>df["c"] = df["b"] * 2
>>>df
  a  b   c
0 10 90  180
1 20 150 300
2 30 -30 -60
Run Code Online (Sandbox Code Playgroud)

然而,这并不像内置函数工作minmax:

>>>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().
Run Code Online (Sandbox Code Playgroud)

有没有办法有效地完成我想要的东西?

jez*_*ael 9

你可以使用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
Run Code Online (Sandbox Code Playgroud)

  • 是的,就是这样!;) (2认同)

Dat*_*Chu 7

您可以跨轴使用 Pandas min 函数。然后将其与最小/最大

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.min.html

例如

df.max(axis=1)
Run Code Online (Sandbox Code Playgroud)

但看起来您想要剪辑这些值而不是最小/最大。