[英]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.