I’m aiming to subset a pandas df using a condition and append those rows to the right of a df. For example, where Num2
is equal to 1
, I want to take the following row and append it to the right of the df
. The following appends every row, where as I just want to append the following row after a 1
in Num2
. I’d also like to be able to append specific cols. Using below, this could be only Num1 and Num2.
JavaScript
x
8
1
df = pd.DataFrame({
2
'Num1' : [0,1,2,3,4,4,0,1,2,3,1,1,2,3,4,0],
3
'Num2' : [0,0,0,0,0,1,3,0,1,2,0,0,0,0,1,4],
4
'Value' : [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
5
})
6
7
df1 = df.add_suffix('1').join(df.shift(-1).add_suffix('2'))
8
intended output:
JavaScript
1
22
22
1
# grab all rows after a 1 in Num2
2
ones = df.loc[df["Num2"].shift().isin([1])]
3
4
# append these to the right
5
Num1 Num2 Value Num12 Num22
6
0 0 0 0
7
1 1 0 0
8
2 2 0 0
9
3 3 0 0
10
4 4 0 0
11
5 4 1 0 0 3
12
6 0 3 0
13
7 1 0 0
14
8 2 1 0 3 2
15
9 3 2 0
16
10 1 0 0
17
11 1 0 0
18
12 2 0 0
19
13 3 0 0
20
14 4 1 0 0 4
21
15 0 4 0
22
Advertisement
Answer
You can try:
JavaScript
1
2
1
df=df.join(df.shift(-1).mask(df['Num2'].ne(1)).drop('Value',1).add_suffix('2'))
2
OR
JavaScript
1
5
1
ones.index=ones.index-1
2
df=df.join(ones.drop('Value',1).add_suffix('2'))
3
#OR(use any 1 since both method doing the same thing)
4
df=pd.concat([df,ones.drop('Value',1).add_suffix('2')],axis=1)
5
If needed use fillna()
:
JavaScript
1
2
1
df[["Num12", "Num22"]]=df[["Num12", "Num22"]].fillna('')
2