0

I have a dataframe named IND_Split as:

    0   1   2   3   4   5   6
0   TY  50                  
1   TY  XT  50              
2   TY  100                 
3   TY  200                 
4   TY  500     

        

What I desire : to get a concatenated single column based on a condition - "if the value in next column is not blank then concatenate with "%20" in between else do not concatenate next column"

Desired output must look like:

    0                       
0   TY%2050                 
1   TY%20XT%2050                
2   TY%20100                    
3   TY%20200                    
4   TY%20500

What I have tried:

IND_Concat = IND_Split[0] + "%20" if IND_Split[1]!='' else ''.....
IND_Concat.head()

Output I got :

enter image description here

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • Have a look at this: https://stackoverflow.com/a/36911306/3376059 I think this is exactly what you are looking for. – OmerM25 Jun 27 '21 at 13:32
  • The above suggested method does not work for me! I need to conditionally put "%20". output from suggested method : eg: TY%2050%20%20%20%20%20 as you can see it unnecessarily adds %20 for columns 3 to 6, which is exactly I don't want! – Parth Sharma Jun 27 '21 at 14:59

1 Answers1

0

Try:

df_out = df.apply(
    lambda x: "%20".join([v for v in x if str(v).strip()]), axis=1
).to_frame()
print(df_out)

Prints:

              0
0       TY%2050
1  TY%20XT%2050
2      TY%20100
3      TY%20200
4      TY%20500
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91