0

I would like to modify the raw data in df1 to the form of df2

import pandas as pd

df1=pd.DataFrame([["20180105","abcdefg"],["","sdasdas"],["20180211","asdasfsd"],["","asdfg"],["","sdada"]],columns=["A","B"])

df2=pd.DataFrame([["20180105","abcdefgsdasdas"],["20180211","asdasfsdasdfgsdada"]],columns=["A","B"])

enter image description here

2 Answers 2

2

Can also use agg + ''.join

g = (df1.A != '').cumsum()
df1.groupby(g, as_index=False).agg(''.join)

    A           B 
0   20180105    abcdefgsdasdas
1   20180211    asdasfsdasdfgsdada
Sign up to request clarification or add additional context in comments.

Comments

2

You can groupby, and use sum for string concatenation:

df1.replace({'A':{'':np.nan}}).ffill().groupby('A', as_index=False).sum() 

          A                   B
0  20180105      abcdefgsdasdas
1  20180211  asdasfsdasdfgsdada

Note I got rid of your blank strings in column A by replacing with NaN and then forward filling with ffill()

1 Comment

Yes, except you should only replace in A in case B contains empty strings too. It's worth pointing out that sum() does what + does, which for strings is concatenation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.