Home > Blockchain >  Merge First Row with the second row of column C if columns A & B are null
Merge First Row with the second row of column C if columns A & B are null

Time:11-04

Need to Merge the second row values with the first row of column C if the rows in columns A&B are null.

DATA:

   A        B       C
12525    1FWE23   1H654D
                  14654        
24798    14654    S56E82
65116    63546    38945        
46456    46485    R68R45
                  AD545    
A5D66    45346    QA6683       

EXPECTED:

   A        B       C
12525    1FWE23   1H654D 14654       
                   
24798    14654    S56E82
65116    63546    38945
46456    46485    R68R45 AD545    
                  
A5D66    45346    QA6683       

CodePudding user response:

You can solve this by shifting column C and concating:

df["C"] = df["C"]   df["C"].shift(-1).fillna("")

Shifting will put NaN in column C for the last row, hence we fill NaN with "".

To filter out the rows that have no value in column A, we do:

df[df["A"] != ""]

>>>

 A       B            C
0  12525  1FWE23  1H654D14654
2  24798   14654  S56E8238945
4  46456   46485  R68R45AD545
6  A5D66   45346       QA6683

CodePudding user response:

@DSteman I have modified your code to merge the rows only if the next row is null.

Here is the below answer and it works fine for me.

df2.loc[df2['A'] != '', 'C'] = df2["C"]   ' '   df2["C"].shift(-1).fillna("")

df2[df2["A"] != '']
  • Related