Jana
Jana

Reputation: 49

Pandas: turn rows into columns

I have a csv file that looks something like this:

0 full_name, Andrew Dean, Milly Mayer,
1 automotive, 216 DYV, ...
...

I now would like to convert this into a pandas df that should look like this

full_name         automotive      ...
Andrew Dean       216 DYV         ...
...               ...                 

Any tips how to solve this?

Upvotes: 0

Views: 291

Answers (1)

user17242583
user17242583

Reputation:

You are looking for DataFrame.T, which is a shortcut for DataFrame.transpose():

>>> df
    full_name Andrew Dean Milly Mayer
0  automotive     216 DYV         xxx

>>> df.T                      0
full_name    automotive
Andrew Dean     216 DYV
Milly Mayer         xxx

Full code:

# Transpose, reset index
df = df.T.reset_index()

# Set column names to be the values of the first row
df.columns = df.iloc[0]

# Remove the first row, reset index
df = df.drop(0).reset_index(drop=True)

# Cleanup columns
df.columns.name = None

Output:

>>> df
     full_name automotive
0  Andrew Dean    216 DYV
1  Milly Mayer        xxx

Upvotes: 1

Related Questions