Stefano Potter
Stefano Potter

Reputation: 3577

Reset index for columns

I have a dataframe like this:

index       1          2
Species  AGRALB     AGRCRI
Count      2          3

but I dont want the first row to be there, I just want the dataframe to look like this:

Species  AGRALB     AGRCRI
Count      2          3

I know you can reset index with df.reset_index() but I only want to do it for the running index in row 1.

Upvotes: 1

Views: 805

Answers (2)

Alexander
Alexander

Reputation: 109726

Try this:

df.columns = df.columns.droplevel()

Docstring: Return Index with requested level removed. If MultiIndex has only 2 levels, the result will be of Index type not MultiIndex.

Parameters ---------- level : int/level name or list thereof

Notes ----- Does not check if result index is unique or not

Returns ------- index : Index or MultiIndex

Upvotes: 1

EdChum
EdChum

Reputation: 394419

It's unclear if 'index' is a column or the name of your index but generically the following will work:

In [23]:
df.columns = df.iloc[0]
df = df.shift(-1).dropna()
df

Out[23]:
0 Species AGRALB AGRCRI
0   Count      2      3

Actually rather than shifting, I'd just take a slice:

In [31]:
df.columns = df.iloc[0]
df = df.iloc[1:]
df

Out[31]:
0 Species AGRALB AGRCRI
1   Count      2      3

If you loaded this data from a csv, and the column names were on the 2nd line then you could just skip the first row df = pd.read_csv(file, skiprows=1)

Upvotes: 1

Related Questions