user3368835
user3368835

Reputation: 367

Making cell entry the name of a column in pandas data frame

Lets say that I have a dataframe (using pandas data analysis library) that looks like so:

   Unnamed Column1:
1  'Puppies'
2  6
3  15
4  13
5  12

And I want to get the dataframe to look like this:

   'Puppies'
1  6
2  15
3  13
4  12
5  80

How does one shift everything up, including entries to replace the column name. Is there a way to do this?

Upvotes: 1

Views: 1220

Answers (1)

unutbu
unutbu

Reputation: 880359

df.columns = df.iloc[0]   # set the columns to the values in the first row
df = df.iloc[1:]          # reassign df to all rows but the first

Note that "Unnamed: 1" sounds suspiciously like the name pd.read_csv assigns to the column if the header row lacked a column name. In that case, instead of patching up the result as shown above, you might be able to fix the problem with skiprows=1 or header=1 instead. skiprows=1 would cause pd.read_csv to skip the first row and thus read the headers (column names) from the second row automatically.

Upvotes: 6

Related Questions