python pandas: Rename a series within a dataframe?

我与影子孤独终老i 提交于 2019-12-08 04:50:34

问题


I'm using python pandas for data analysis and I want to change the name of a series in a dataframe.

This works, but it seems very inefficient:

AA = pandas.DataFrame( A )
for series in A:
    AA[A_prefix+series] = A[series]
    del A[series]

Is there a way to change the series name in place?


回答1:


Sure, you can use the rename method:

In [11]: df = DataFrame({"A": [1,2], "B": [3,4]})

In [12]: df.rename(columns={"A": "series formerly known as A"})
Out[12]: 
   series formerly known as A  B
0                           1  3
1                           2  4

This doesn't change df, though:

In [13]: df
Out[13]: 
   A  B
0  1  3
1  2  4

You can get that behaviour if you want using inplace:

In [14]: df.rename(columns={"A": "series formerly known as A"}, inplace=True)
Out[14]: 
   series formerly known as A  B
0                           1  3
1                           2  4

In [15]: df
Out[15]: 
   series formerly known as A  B
0                           1  3
1                           2  4


来源:https://stackoverflow.com/questions/12201099/python-pandas-rename-a-series-within-a-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!