简体   繁体   中英

Python Pandas trasnpose DataFrame and rename columns

Here's a simple DataFrame example:

import pandas as pd

d = dict(
    column1 = [1, 'a', 'foo'],
    column2 = [2, 'b', 'bar'],
    column3 = [3, 'c', 'baz'],
)
df = pd.DataFrame(data=d)
print(df)

with the output

  column1 column2 column3
0     1     2     3
1     a     b     c
2   foo   bar   baz

I want to transpose it and rename the columns:

df.do_some_manipulation('numbers', 'letters', 'words')

so the output would be

   numbers letters words
0        1       a   foo
1        2       b   bar
2        3       c   baz

Transpose method is not quite the thing, what should I do then?

A better option would be pd.DataFrame.from_dict with the index orient:

pd.DataFrame.from_dict(d, orient='index', columns=['numbers', 'letters', 'words'])

         numbers letters words
column1        1       a   foo
column2        2       b   bar
column3        3       c   baz

Try this:

df = df.T
df.columns = ['numbers', 'letters', 'words']
df = df.reset_index(drop = True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM