分配等于值的列 - pandas df

Assign Column where equal to value - pandas df

我正在尝试 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

您可以使用系列蒙版和 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

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

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

加速约为 1000 倍