redplanet
redplanet

Reputation: 65

add a new column in dataframe

I have one data frame and I want to add one more column

the data frame has 29793 rows. So I want the new column to goes down to the end of the data frame

I try some things. in the begging a declare the column and the value like activity = ["sitting"]

then I try to add to the existing data frame

a['activity'] = activity

but I get the following error

ValueError: Length of values does not match the length of the index

how to fix this. Any ideas?

EDIT:

Is there a way to add the column in the begging of the data frame (left side) because now is appended in the right side

Upvotes: 1

Views: 244

Answers (2)

jezrael
jezrael

Reputation: 862396

Set new column by scalar by select first value in one element list:

activity = ["sitting"]
a['activity'] = activity[0]

Or remove [] for scalar:

activity = "sitting"
a['activity'] = activity

EDIT:

Use DataFrame.insert for create new column from left side, in position 0:

a.insert(0, 'activity', activity)

what is same like:

a.insert(0, 'activity', "sitting")

Upvotes: 1

Mayank Porwal
Mayank Porwal

Reputation: 34046

This:

a['activity'] = 'sitting'

Upvotes: 1

Related Questions