Merge rows based on condtion

Viewed 55

I have data Frame like below

enter image description here

And I want merge "Transaction Particulars" index of 24,25 and 26 on index of 25 , same as merge Transaction Particulars index of 28,29 and 30 on index of 29 And this merge based on Tran Date if Above and below value of Tran Date is Nan then merge all this three index on Tran Date value index

i try with

tm['originalIdx'] = tm.apply(lambda x:x.name if x['Tran Date']!='' else None, axis=1).ffill()

tm = pd.merge(tm.drop('Transaction Particulars', axis=1),
            pd.DataFrame(tm.groupby(['originalIdx'])['Transaction Particulars'].apply(lambda x: " ".join(x))),
            left_index=True, right_index=True, how='left')
1 Answers

here is the answer

tm = tm[~tm['Tran Date'].str.match(r'^\D', na=False)].replace(np.nan,'')

tm['originalIdx'] = tm.apply(lambda x:x.name if x['Tran Date']!='' else None, axis=1).bfill(limit=1).ffill(limit=2)

tm = pd.merge(tm.drop('Transaction Particulars', axis=1), 
    pd.DataFrame(tm.groupby(['originalIdx'])['Transaction Particulars'].apply(lambda x: " ".join(str(v) for v in x))),
    left_index=True, right_index=True, how='left')

using this code i solved my problem

Related