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.
df = pd.DataFrame({ 'Num1' : [0,1,2,3,4,4,0,1,2,3,1,1,2,3,4,0], 'Num2' : [0,0,0,0,0,1,3,0,1,2,0,0,0,0,1,4], 'Value' : [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] }) df1 = df.add_suffix('1').join(df.shift(-1).add_suffix('2'))
intended output:
# grab all rows after a 1 in Num2 ones = df.loc[df["Num2"].shift().isin([1])] # append these to the right Num1 Num2 Value Num12 Num22 0 0 0 0 1 1 0 0 2 2 0 0 3 3 0 0 4 4 0 0 5 4 1 0 0 3 6 0 3 0 7 1 0 0 8 2 1 0 3 2 9 3 2 0 10 1 0 0 11 1 0 0 12 2 0 0 13 3 0 0 14 4 1 0 0 4 15 0 4 0
Advertisement
Answer
You can try:
df=df.join(df.shift(-1).mask(df['Num2'].ne(1)).drop('Value',1).add_suffix('2'))
OR
ones.index=ones.index-1 df=df.join(ones.drop('Value',1).add_suffix('2')) #OR(use any 1 since both method doing the same thing) df=pd.concat([df,ones.drop('Value',1).add_suffix('2')],axis=1)
If needed use fillna()
:
df[["Num12", "Num22"]]=df[["Num12", "Num22"]].fillna('')