R.Aarthika Rajendran
R.Aarthika Rajendran

Reputation: 125

append the data in python

I have one csv file like this

out.csv
seedProductId,relatedProducts

My output is in dftype object looks like this

100A7E54111FB143    
100D11CF822BBBDB    
1014120EE9CCB1E0    
10276825CD5B4A26    
10364F56076B46B7    
103D1DDAD3064A66    
103F4F66EEB54308    

I want to append this output with delimiter '|'.And I will pass another input as dynamic.

so I want the op like this

out.csv
seedProductId, relatedProducts
103F4F66EEB54308, 100A7E54111FB143 | 100D11CF822BBBDB | 10276825CD5B4A26 ...

Any help will be appreciated.

Upvotes: 1

Views: 48

Answers (1)

jezrael
jezrael

Reputation: 862481

You can use cat for merging data, then create new Series for each columns and concat them. Last write output dataframe to file by to_csv:

print df
                  A
0  100A7E54111FB143
1  100D11CF822BBBDB
2  1014120EE9CCB1E0
3  10276825CD5B4A26
4  10364F56076B46B7
5  103D1DDAD3064A66
6  103F4F66EEB54308

seedProductId = "id790"
s1 = pd.Series(seedProductId, name='seedProductId')
print s1
0    id790
Name: seedProductId, dtype: object

relatedProducts = df.A.str.cat(sep='|')
print relatedProducts
100A7E54111FB143|100D11CF822BBBDB|1014120EE9CCB1E0|10276825CD5B4A26|10364F56076B46B7|103D1DDAD3064A66|103F4F66EEB54308

s2 = pd.Series(relatedProducts, name='relatedProducts')
print s2
0    100A7E54111FB143|100D11CF822BBBDB|1014120EE9CC...
Name: relatedProducts, dtype: object

df = pd.concat([s1, s2], axis=1)

print df.to_csv(index=False)
seedProductId,relatedProducts
id790,100A7E54111FB143|100D11CF822BBBDB|1014120EE9CCB1E0|10276825CD5B4A26|10364F56076B46B7|103D1DDAD3064A66|103F4F66EEB54308

Upvotes: 1

Related Questions