How to Change Column Names of Pandas DataFrame?

How to Change Column Names of Pandas DataFrame?

Pandas DataFrame C 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 C 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({

'a':[14,pandas

52, 46],

import

as pd

'b':[32, 85, 64],

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

#initialize a dataframe

#change column names

df = pd.DataFrame({

df.columns

= ['d', 'e',

'f'] 'a':[14, 52, 46],

#print

the dataframe

'b':[32,

85, 64],

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

def

0 14 32 88

1 52 85 47

2 46 64 36

Example C [Negative Scenario] C 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({

'a':[14,pandas

52, 46],

import

as pd

'b':[32, 85, 64],

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

#initialize a dataframe

#change column names

df = pd.DataFrame({

df.columns

= ['d', 'e',

'f', 'g']

'a':[14, 52, 46],

#print

the dataframe

'b':[32,

85, 64],

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

elements

ValueError: 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