I have a pandas dataframe with 7 columns.
The first three columns already have a column name (for example: ['Apple', 'Banana', 'Strawberry']
.
I want to set the other 4 columns names as ones from a list. I have a list with the following 4: ['Square','Round','Circle','Triangle']
I would like to create a dataframe with 7 columns with the following names: ['Apple','Banana','Strawberry','Square','Round','Circle','Triangle']
. Is this even possible?
CodePudding user response:
Ideally, you'd just be able to do this:
df.columns[3:] = ['Square','Round','Circle','Triangle']
But you can't modify the existing index, so you need to assign a whole new one:
df.columns = df.columns[:3].tolist() ['Square','Round','Circle','Triangle']
CodePudding user response:
Here, a bit of an example of what you can do
import pandas as pd
# Create a dataframe with columns a, b
columnNames = ['a','b']
myData = pd.DataFrame(columns=columnNames)
# Append columnNames to existing ones
columnNames = ['c','d']
myData.columns = columnNames
# Rename all columns with new ones
columnNames = ['e','f','g','h']
myData.columns = columnNames