How to Change Column Names of Pandas DataFrame?

How to Change Column Names of Pandas DataFrame?

Pandas DataFrame ? Change Column Names

You can access Pandas DataFrame columns using DataFrame.columns property. We can assign an array with new column names to the DataFrame.columns property.

Note: Length of new column names arrays should match number of columns in the DataFrame.

Example ? Change Column Names of Pandas DataFrame

In the following example, we take a DataFrame with some initial column names and change these column names to new values.

Python Example

import pandas as pd #initialize a dataframe df = pd.DataFrame({ i'ma'p:[o1rt4,p5a2n,da4s6]a,s pd 'b':[32, 85, 64], 'c':[88, 47, 36]}) #initialize a dataframe #change column names ddff.c=olpudm.nDsat=aF[r'da'm, e'e('{, 'f'] 'a':[14, 52, 46], #pri'nbt':[t3h2e, d8a5t,a6fr4a]m, e print(df)

'c':[88, 47, 36]})

#change column names df.columns = ['d', 'e', 'f']

#print the dataframe print(df)

Output

d e f 0 14 32 88 1 52 85 47 2 46 64 36

d e f 0 14 32 88 1 52 85 47 2 46 64 36

Example ? [Negative Scenario] ? When new column names array length not same as that of columns in DataFrame

In this example, we shall assign DataFrame.columns an array that has length greater than that of columns in the DataFrame.

Python Example

import pandas as pd #initialize a dataframe df = pd.DataFrame({ i'ma'p:[o1rt4,p5a2n,da4s6]a,s pd 'b':[32, 85, 64], 'c':[88, 47, 36]}) #initialize a dataframe #change column names ddff.c=olpudm.nDsat=aF[r'da'm, e'e('{, 'f', ''ga'']:[14, 52, 46], #pri'nbt':[t3h2e, d8a5t,a6fr4a]m, e print(df)

'c':[88, 47, 36]})

#change column names df.columns = ['d', 'e', 'f', 'g']

#print the dataframe print(df)

Output

ValueError: Length mismatch: Expected axis has 3 elements, new values have 4 eVleamluenEtrsror: Length mismatch: Expected axis has 3 elements, new values have 4 elements

We get a Value Error with the message that there is a length mismatch for old column names and new column namess.

Conclusion

In this Pandas Tutorial, we learned how to change the column names of a DataFrame.

Python Pandas

Pandas Tutorial Pandas DataFrame - Change Column Names Pandas DataFrame - Add or Append Row Pandas DataFrame - Add new column Pandas DataFrame - Delete Column

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download