简体   繁体   中英

Pandas: Name the unmaed column of dataframe

I have dataframe that has one column but it does not have any name as shown in the figure below.

在此处输入图像描述

Now I want to name the unnamed coulmn. I looked at the existing thread ( Rename unnamed column pandas dataframe ) and wrote the following code:

temp.rename(columns = {0:'SUBGROUP'},inplace=True)

but it didn't produce the desired result. Could anyone point out where am I making the mistake?

First of all, it needs to be clear that the Pandas Series is 1D data, the Series name is the column name you want, and it is displayed below when printed. If you want to get the effect that the column name you expect appears above the column value, you must convert the data type to the DataFrame type of pandas.


Demo

import pandas as pd

# build Series temp with first 3 row data of your example
temp = pd.Series(data=["DA33", "", "FK33-2"], index=[70015,69999, 69998])
temp.index.name = "SITE_NUMBER"
temp.name = "FEEDERID"
print(type(temp))
print(temp)

# transform type from Series to DataFrame
# you see the name of Series should beoome the column name of DataFrame
temp = pd.DataFrame(data=temp)
print(type(temp))
print(temp)

演示展示

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