简体   繁体   English

根据当前行和上一行的数据为数据帧分配新列

[英]Assign a new column to dataframe based on data from current row and previous row

I have 2 columns of data called level 1 event and level 2 event. 我有2列数据,称为1级事件和2级事件。
Both are columns of 1s and zeros. 两者都是1和0的列。

lev_1 lev_2 lev_2_&_lev_1
0    1    0      0
1    0    0      0
2    1    0      0
3    1    1      1
4    1    0      0

col['lev2_&_lev_1] = 1 if lev_2 of current row and lev_1 of previous row are both 1. col['lev2_&_lev_1] = 1如果lev_2当前行和lev_1前一行的都是1。
I have achieved this by using for loop. 我通过使用for循环实现了这一点。

i = 1  
while i < a.shape[0]:
    if a['lev_1'].iloc[i - 1] == 1 &  a['lev_2'].iloc[i] == 1:
        a['lev_2_&_lev_1'].iloc[i] = 1
    i += 1

I wanted to know a computationally efficient way to do this because my original df is very big. 我想知道一种计算效率高的方法,因为我的原始df非常大。
Thank you! 谢谢!

你要:

(df['lev_2'] & df['lev_1'].shift()).astype(int)

Use np.where and .shift() : 使用np.where.shift()

df['lev_2_&_lev_1'] = np.where(df['lev_2'].eq(1) & df['lev_1'].shift().eq(1), 1, 0)

   lev_1  lev_2  lev_2_&_lev_1
0      1      0              0
1      0      0              0
2      1      0              0
3      1      1              1
4      1      0              0

Explanation 说明

  • df['lev_2'].eq(1) : checks if current row is equal to 1 df['lev_2'].eq(1) :检查当前行是否等于1
  • df['lev_1'].shift().eq(1) : checks if previous row is equal to 1 df['lev_1'].shift().eq(1) :检查前一行是否等于1
  • np.where(condition, 1, 0) : if condition is True return 1 else 0 np.where(condition, 1, 0) :如果condition为True返回1否则为0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据上一个行值创建一个新列并删除当前行 - Create a new column based on previous row value and delete the current row 有没有办法根据现有列的当前和前一行值在每行的新列中分配增量值的数量? - Is there a way to assign number of incremental value in a new column of each rows based current and previous row values of existing columns? 如何从 pandas dataframe 中的当前行中减去前一行以创建一个新列,以每个名称重新启动进程? - How to subtract previous row from current row in a pandas dataframe to create a new column restarting the process with each name? 根据前一行将数据添加到新列 - Add data to new column based on previous row 根据上一行的值在熊猫数据框中创建一个新列 - Create a new column in a pandas dataframe based on values found on a previous row Pandas DataFrame:添加具有基于前一行计算值的新列 - Pandas DataFrame: Add new column with calculated values based on previous row 比较后将当前行值分配给熊猫数据帧的前一行 - Assign current row value to previous row of panda dataframe after comparison Spark使用上一行的值将新列添加到数据框 - Spark add new column to dataframe with value from previous row Python Pandas Dataframe 根据同一列中的前一行值计算新行值 - Python Pandas Dataframe calculating new row value based on previous row value within same column 如何根据 Pandas dataframe 中上一行的行值创建新列? - How to create a new column based on row value in previous row in Pandas dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM