简体   繁体   English

Python Pandas转置DataFrame并重命名列

[英]Python Pandas trasnpose DataFrame and rename columns

Here's a simple DataFrame example: 这是一个简单的DataFrame示例:

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 ,其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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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