Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to (re)name an empty column header in a pandas dataframe without exporting to csv

I have a pandas dataframe df1 with an index column and an unnamed series of values. I want to assign a name to the unnamed series.

The only way to do this that I know so far is to export to df1.csv using:

df1.to_csv("df1.csv", header = ["Signal"])

and then re-import using:

pd.read_csv("df1.csv", sep=",")

However, this costs time and storage space. How to do this in-memory?

When I do df2 = df1.rename(columns = {"" : "Signal"}, inplace = True)

I yield:

AttributeError: "Series" object has no attribute "Signal".

like image 366
sudonym Avatar asked Dec 12 '16 08:12

sudonym


People also ask

How do I rename blank columns in pandas?

Sometimes we want to rename columns and indexes in the Pandas DataFrame object. We can use pandas DataFrame rename() function to rename columns and indexes. It supports the following parameters. mapper: dictionary or a function to apply on the columns and indexes.

How do you name a column with no name in pandas DataFrame?

rename( columns={0 :'new column name'}, inplace=True ) . There is no need to use 'Unnamed: 0' , simply use the column number, which is 0 in this case and then supply the 'new column name' .


2 Answers

I think inplace=True has to be removed, because it return None:

df2 = df1.rename(columns = {"" : "Signal"})

df1.rename(columns = {"" : "Signal"}, inplace = True)

Another solution is asign new name by position:

df.columns.values[0] = 'Signal'

Sample:

df1 = pd.DataFrame({'':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9]})

print (df1)
      B  C
0  1  4  7
1  2  5  8
2  3  6  9

df2 = df1.rename(columns = {"" : "Signal"})
print (df2)
   Signal  B  C
0       1  4  7
1       2  5  8
2       3  6  9
like image 108
jezrael Avatar answered Oct 17 '22 12:10

jezrael


You can use this if there are multiple empty columns. This will generate an empty column with cols and i (for the column position)

df.columns = ["cols_"+str(i) if a == "" else a for i, a in enumerate(df.columns)]

#cols -> just rename the column name just as you want
#i -> count the column number
like image 34
agusdd Avatar answered Oct 17 '22 12:10

agusdd