Home > OS >  can i rename all rows/columns of very large dataset at once in python?
can i rename all rows/columns of very large dataset at once in python?

Time:11-03

I want to rename all of my rows names at once in python

This is example ( in R ) of what I want :

names(dataframe) <- c(paste0("G",1:7129),"class")

CodePudding user response:

In python you can change columns using pandas like this :

df.rename(columns={"A": "a", "B": "c"})

If you want rename index :

df.rename(index={0: "x", 1: "y", 2: "z"})

CodePudding user response:

You can use pandas rename function to rename columns like:

df.rename(columns={'old_column1_name':'new_col1_name','old_column2_name':'new_col2_name'}, inplace=True)

If you have thousands of columns and want the same name for every column do something like:

df.rename(columns={i:'new_column_name' for i in df.columns}, inplace = True)

CodePudding user response:

Can you elaborate more about what kind of rename you want(with an example, and also explain the R code also)?

Here in the below example, I am replacing all white space ' ' in the column names with '_', and it will work with any number of columns(You can use this for replacing different character using regex, concat a characters also).

import pandas as pd

df=pd.DataFrame({'Full Name':['Tom', 'nick', 'krish', 'jack'],
        'salary per year':[20, 21, 19, 18],
    'F1 Name':['Tom', 'nick', 'krish', 'jack'],
    'F2 Name':['Tom', 'nick', 'krish', 'jack'],
    'F3 Name':['Tom', 'nick', 'krish', 'jack'],
    'F4 Name':['Tom', 'nick', 'krish', 'jack']
})

print(df)
df.columns = df.columns.str.replace(' ', '_')
print(df)

Output of the above program is :

Full Name  salary per year F1 Name F2 Name F3 Name F4 Name
0       Tom               20     Tom     Tom     Tom     Tom
1      nick               21    nick    nick    nick    nick
2     krish               19   krish   krish   krish   krish
3      jack               18    jack    jack    jack    jack
Full_Name  salary_per_year F1_Name F2_Name F3_Name F4_Name
0       Tom               20     Tom     Tom     Tom     Tom
1      nick               21    nick    nick    nick    nick
2     krish               19   krish   krish   krish   krish
3      jack               18    jack    jack    jack    jack

Here, this thread, you can find different ways to replace white space to '_'.

  • Related