Tianjiang2016
Tianjiang2016

Reputation: 1

how to join one row in using the comma in python?

I have created a dataframe like this. My purpose is go join the character of each row of dataframe, like '10,0' for the first row. How can I do that? Thanks.

import pandas as pd
df = pd.DataFrame({'a': range(10,20),'b': range(0,10)})

>>df
    a  b
0  10  0
1  11  1
2  12  2
3  13  3
4  14  4
5  15  5
6  16  6
7  17  7
8  18  8
9  19  9

Upvotes: 0

Views: 94

Answers (2)

Merlin
Merlin

Reputation: 25659

Try this: Uses List Comprehension to return list.

[ str(x[0]) + "," + str(x[1]) for x in df.values.tolist()]

['10,0',
 '11,1',
 '12,2',
 '13,3',
 '14,4',
 '15,5',
 '16,6',
 '17,7',
 '18,8',
 '19,9']

Upvotes: 0

Ashish Ranjan
Ashish Ranjan

Reputation: 5543

You can do it like this :

import pandas as pd
df = pd.DataFrame({'a': range(10,20),'b': range(0,10)})
valueList = []
for i in range(len(df)):
    valueList.append(str(df['a'][i]) + "," + str(df['b'][i]))
print valueList

OUTPUT :

['10,0', '11,1', '12,2', '13,3', '14,4', '15,5', '16,6', '17,7', '18,8', '19,9']

or simply :

import pandas as pd
df = pd.DataFrame({'a': range(10,20),'b': range(0,10)})

print [",".join(map(str, pairs)) for pairs in zip(df['a'],df['b'])]

OUTPUT :

['10,0', '11,1', '12,2', '13,3', '14,4', '15,5', '16,6', '17,7', '18,8', '19,9']

Upvotes: 1

Related Questions