10 python numpy minimum dataframe pandas
我想为给定的数据帧创建新列,其中我计算列值和某个全局值之间的最小值(在此示例中为7).所以我的DF具有列session和note我期望的输出列minValue:
session note minValue
1 0.726841 0.726841
2 3.163402 3.163402
3 2.844161 2.844161
4 NaN NaN
Run Code Online (Sandbox Code Playgroud)
我正在使用内置的Python方法min:
df['minValue']=min(7, df['note'])
Run Code Online (Sandbox Code Playgroud)
我有这个错误:
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)
EdC*_*ica 12
用途np.minimum:
In [341]:
df['MinNote'] = np.minimum(1,df['note'])
df
Out[341]:
session note minValue MinNote
0 1 0.726841 0.726841 0.726841
1 2 3.163402 3.163402 1.000000
2 3 2.844161 2.844161 1.000000
3 4 NaN NaN NaN
Run Code Online (Sandbox Code Playgroud)
也min不能理解阵列喜欢攀比,因此你的错误
执行此操作的首选方法pandas是使用Series.clip()方法。
在您的示例中:
import pandas
df = pandas.DataFrame({'session': [1, 2, 3, 4],
'note': [0.726841, 3.163402, 2.844161, float('NaN')]})
df['minVaue'] = df['note'].clip(upper=1.)
df
Run Code Online (Sandbox Code Playgroud)
将返回:
note session minVaue
0 0.726841 1 0.726841
1 3.163402 2 1.000000
2 2.844161 3 1.000000
3 NaN 4 NaN
Run Code Online (Sandbox Code Playgroud)
numpy.minimum也可以,但是.clip()有一些优点:
df['note'].clip(lower=0., upper=10.)df['note'].abs().clip(upper=1.).round()| 归档时间: |
|
| 查看次数: |
5438 次 |
| 最近记录: |