Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple columns into 1 column [python,pandas]

Tags:

python

pandas

I have a pandas data frame with 2 columns: {'A':[1, 2, 3],'B':[4, 5, 6]}

I want to create a new column where: {'C':[1 4,2 5,3 6]}

like image 311
Javiar Sandra Avatar asked Oct 25 '25 06:10

Javiar Sandra


2 Answers

Setup

df = pd.DataFrame({'A':[1, 2, 3],'B':[4, 5, 6]})

Solution

Keep in mind, per your expected output, [1 4,2 5,3 6] isn't a thing. I'm interpreting you to mean either [(1, 4), (2, 5), (3, 6)] or ["1 4", "2 5", "3 6"]

First assumption

df.apply(lambda x: tuple(x.values), axis=1)

0    (1, 4)
1    (2, 5)
2    (3, 6)
dtype: object

Second assumption

df.apply(lambda x: ' '.join(x.astype(str)), axis=1)

0    1 4
1    2 5
2    3 6
dtype: object
like image 58
piRSquared Avatar answered Oct 27 '25 21:10

piRSquared


If you don't mind zip object, then you can usedf['C'] = zip(df.A,df.B). If you like tuple then you can cast zip object with list(). Please refer to this post. It's pretty handy to use zip in this kind of scenarios.

like image 27
Andreas Hsieh Avatar answered Oct 27 '25 19:10

Andreas Hsieh