eric22
eric22

Reputation: 13

How can I put together several csv file columns into a single column using Pandas?

I have 7 columns in a csv file containing info that I would like to be able to merge together and process. How can I do this using Pandas library.

Upvotes: 0

Views: 40

Answers (2)

ASH
ASH

Reputation: 20302

This is one way to do it.

import pandas as pd
df = pd.DataFrame()
df['Name'] = ['John', 'Doe', 'Bill']
df['Age'] = [12, 12, 13]
df

enter image description here

df['single'] = df['Name'] + "_" +  df['Age'].astype(str)
df

enter image description here

Upvotes: 0

Rayan Hatout
Rayan Hatout

Reputation: 640

You can use the stack method of DataFrames. The code would look like this:

original_df = pd.DataFrame([['a', 'b'], ['c', 'd']])
print(original_df)
#    0  1
# 0  'a'  'b'
# 1  'c'  'd'

stacked = original_df.stack()
print(stacked)
# 0  0    'a'
#    1    'b'
# 1  0    'c'
#    1    'd'
# dtype: object

Do note that stacked isn't a DataFrame anymore but rather a Series object with a multi-level index.

Upvotes: 1

Related Questions