将Column赋值等于value - pandas df

问题描述 投票:0回答:2

我试图在assign pandas df值。具体来说,对于下面的df,我想使用Column['On']来确定当前发生了多少个值。然后我想将这些值分配给3组。所以价值观;

1-3 = 1
4-6 = 2
7-9 = 3 etc

这可以达到20-30个值。我考虑过np.where,但效率不高,而且我返回错误。

import pandas as pd
import numpy as np

d = ({                
    'On' : [1,2,3,4,5,6,7,7,6,5,4,3,2,1],                                     
      })

df = pd.DataFrame(data=d)

此通话有效:

df['P'] = np.where(df['On'] == 1, df['On'],1)

但如果我想将此应用于其他值,我会收到错误:

df = df['P'] = np.where(df['On'] == 1, df['On'],1)
df = df['P'] = np.where(df['On'] == 2, df['On'],1)
df = df['P'] = np.where(df['On'] == 3, df['On'],1)

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
python pandas dataframe group-by where
2个回答
1
投票

你可以使用系列面具和loc

df['P'] = float('nan')
df['P'].loc[(df['On'] >= 1) & (df['On'] <= 3)] = 1
df['P'].loc[(df['On'] >= 4) & (df['On'] <= 6)] = 2
# ...etc

通过循环扩展它非常容易

j = 1
for i in range(1, 20):
    df['P'].loc[(df['On'] >= j) & (df['On'] <= (j+2))] = i
    j += 3

1
投票

通过一些基本的数学和矢量化,您可以获得更好的表现。

import pandas as pd
import numpy as np
n = 1000 
df = pd.DataFrame({"On":np.random.randint(1,20, n)})

AlexG的解决方案

%%time
j = 1
df["P"] =  np.nan
for i in range(1, 20):
    df['P'].loc[(df['On'] >= j) & (df['On'] <= (j+2))] = i
    j += 3

CPU times: user 2.11 s, sys: 0 ns, total: 2.11 s
Wall time: 2.11 s

建议的解决方案

%%time
df["P"] = np.ceil(df["On"]/3)


CPU times: user 2.48 ms, sys: 0 ns, total: 2.48 ms
Wall time: 2.15 ms

加速是~1000x

© www.soinside.com 2019 - 2024. All rights reserved.