Python Pandas Dataframe:将数据归一化到0.01到0.99之间?

jfi*_*ive 2 python normalization dataframe pandas

我试图将数据帧中的每个值绑定在0.01和0.99之间

我使用以下方法成功地将0到1之间的数据标准化:.apply(lambda x: (x - x.min()) / (x.max() - x.min()))如下:

df = pd.DataFrame({'one' : ['AAL', 'AAL', 'AAPL', 'AAPL'], 'two' : [1, 1, 5, 5], 'three' : [4,4,2,2]})

df[['two', 'three']].apply(lambda x: (x - x.min()) / (x.max() - x.min()))

df
Run Code Online (Sandbox Code Playgroud)

现在我想绑定0.01到0.99之间的所有值

这是我尝试过的:

def bound_x(x):
    if x == 1:
        return x - 0.01
    elif x < 0.99:
        return x + 0.01

df[['two', 'three']].apply(bound_x)
Run Code Online (Sandbox Code Playgroud)

df

但是我收到以下错误:

ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', u'occurred at index two')
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 11

有一个app,错误的剪辑方法,为此:

import pandas as pd
df = pd.DataFrame({'one' : ['AAL', 'AAL', 'AAPL', 'AAPL'], 'two' : [1, 1, 5, 5], 'three' : [4,4,2,2]})    
df = df[['two', 'three']].apply(lambda x: (x - x.min()) / (x.max() - x.min()))
df = df.clip(lower=0.01, upper=0.99)
Run Code Online (Sandbox Code Playgroud)

产量

    two  three
0  0.01   0.99
1  0.01   0.99
2  0.99   0.01
3  0.99   0.01
Run Code Online (Sandbox Code Playgroud)

这个问题

df[['two', 'three']].apply(bound_x)
Run Code Online (Sandbox Code Playgroud)

这是bound_x传递类似的系列df['two'],然后if x == 1需要在布尔上下文中x == 1进行评估.x == 1是一个布尔系列之类的

In [44]: df['two'] == 1
Out[44]: 
0    False
1    False
2     True
3     True
Name: two, dtype: bool
Run Code Online (Sandbox Code Playgroud)

Python尝试将此系列减少为单个布尔值,True或False.当您尝试将Series(或数组)转换为bool时,Pandas遵循NumPy 提出错误的约定.