如何使用python shift函数通过使用特定列的前一行值来增加单元格的值?

时间:2019-02-15 08:04:08

标签: python dataframe

我有一个带有布尔值的列“ Y”的数据框。我想创建一个新列X,该列取决于Y和X本身的值。因此,如果Y为False,我希望X的值为1,如果Y为True,我希望X的值为X的前一行值+1。我需要以下输出:

Y     X
False 1
True  2
True  3
False 1
False 1
True  2
True  3

我正在尝试移位函数df.loc [df ['Y'] == True,'X'] = df.X.shift(1)+1 但没有获得所需的输出。我得到的输出为

    Y   X
0   False   1.0
1   True    2.0
2   True    2.0
3   False   1.0
4   False   1.0
5   True    2.0
6   True    2.0

第二次Y具有True值时,应使用先前的X值将X递增1。

我不喜欢循环/迭代,因为我有500万行数据,迭代需要花费数小时的处理时间。

df.loc[df['Y']==True,'X'] = df.X.shift(1)+1

columns = ['Y']
index =0,1,2,3,4,5,6
df = pd.DataFrame(index=index, columns=columns)
df['Y'] = True
df.loc[0,'Y']= False
df.loc[3,'Y']= False
df.loc[4,'Y']= False

df.loc[:,'X']=1
df.loc[df['Y']==True,'X'] = df.X.shift(1)+1

1 个答案:

答案 0 :(得分:1)

我担心班次无法处理这种情况,至少我尝试了很多次。

这里提供了另一种处理方式。

## your codes about initializing df

import pandas as pd
import numpy as np

columns = ['Y']
index = 0, 1, 2, 3, 4, 5, 6
df = pd.DataFrame(index=index, columns=columns)
df['Y'] = True
df.loc[0, 'Y'] = False
df.loc[3, 'Y'] = False
df.loc[4, 'Y'] = False

df.loc[:, 'X'] = 1

print(df)

### initializing of df ends here

### my codes start here


# create an assist column holding the cumsum of X column
df['cum'] = df.X.cumsum()

# calculate the offset
df['offset'] = df.apply(lambda s: 0 - s.cum if s.Y is False else np.nan, axis=1).fillna(method='ffill') + 1

# modify the X column by cumsum and calculated offset
df['X'] = df['cum'] + df['offset']

df.X = df.X.astype(int)
# remove assist columns leaving only the Y, X column
df = df[['Y', 'X']]

print(df)

结果看起来像这样,我想这正是您急需的,并且由于它使用熊猫进行计算,因此不会像纯Python代码中的for循环那样慢:

       Y  X
0  False  1
1   True  1
2   True  1
3  False  1
4  False  1
5   True  1
6   True  1

       Y  X
0  False  1
1   True  2
2   True  3
3  False  1
4  False  1
5   True  2
6   True  3

您可以在删除这两列(加,偏移)之前添加 print(df),以查看有关数据框外观的更多详细信息。

计算累积偏移量列:

       Y  X  cum  offset
0  False  1    1     0.0
1   True  1    2     0.0
2   True  1    3     0.0
3  False  1    4    -3.0
4  False  1    5    -4.0
5   True  1    6    -4.0
6   True  1    7    -4.0

更新X列:

       Y    X  cum  offset
0  False  1.0    1     0.0
1   True  2.0    2     0.0
2   True  3.0    3     0.0
3  False  1.0    4    -3.0
4  False  1.0    5    -4.0
5   True  2.0    6    -4.0
6   True  3.0    7    -4.0