本文是小编为大家收集整理的关于获取一列的[0, x]元素的最小值的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。
问题描述
我需要计算一个列,其中该值是其他列的矢量化操作的结果:
df["new_col"] = df["col1"] - min(0,df["col2"])
事实证明,我不能像上面的语法中使用最小.那么,获取最小的零和给定值之间的最小值的正确方法是什么?
推荐答案
您可以使用 >查找数组的最低元素
import numpy as np df["new_col"] = df["col1"] - np.minimum(0,df["col2"])
其他推荐答案
您可以使用一些掩码和临时列.完全忽略了"最小"功能.
magicnumber = 0 tempcol = df['col2'] mask = tempcol < magicnumber tempcol.loc[df[~mask].index] = magicnumber df['col1'] - tempcol
或者您可以使用lambda函数:
magicnumber = 0 df['col1'] - df['col2'].apply(lambda x: np.min(magicnumber, x))
或者您可以在两列上应用:
df['magicnumber'] = 0 df['col1'] - df[['col2', 'magicnumber']].apply(np.min, axis=1)
其他推荐答案
我认为其他答案不是您的意思.他们在df['col2']中使用最小值,并将其与0进行比较(因此始终返回相同的值),而您希望在col2和0中的每个值之间的最小值:
中的每个值之间的最小值.df = pd.DataFrame(data={'a': [2, 3], 'b': [-1, 1]}) df['new_col'] = map(lambda a, b: a - min(0, b), df['a'], df['b']) print df >> a b new_col 0 2 -1 3 1 3 1 3
问题描述
I need to compute a column where the value is the result of a vectorized operation over other columns:
df["new_col"] = df["col1"] - min(0,df["col2"])
It turned out, however, that I cannot use min as in the above syntax. So, what is the right way to get the min between zero and a given value of pandas column?
推荐答案
you can use numpy.minimum to find the element-wise minimum of an array
import numpy as np df["new_col"] = df["col1"] - np.minimum(0,df["col2"])
其他推荐答案
You could use some masking and a temporary column. Totally ignoring the 'min' function.
magicnumber = 0 tempcol = df['col2'] mask = tempcol < magicnumber tempcol.loc[df[~mask].index] = magicnumber df['col1'] - tempcol
Or you can use a lambda function:
magicnumber = 0 df['col1'] - df['col2'].apply(lambda x: np.min(magicnumber, x))
OR you can apply over two columns:
df['magicnumber'] = 0 df['col1'] - df[['col2', 'magicnumber']].apply(np.min, axis=1)
其他推荐答案
I think that the other answers aren't what you meant. They take the minimum value in df['col2'] and compare it to 0 (and thus always return the same value), while you wanted the minimum between each value in col2 and 0:
df = pd.DataFrame(data={'a': [2, 3], 'b': [-1, 1]}) df['new_col'] = map(lambda a, b: a - min(0, b), df['a'], df['b']) print df >> a b new_col 0 2 -1 3 1 3 1 3