r4sk01
r4sk01

Reputation: 19

How to add Column vector to Data Frame (Python, Pandas)

I have a df with 365 rows × 8 columns.

enter image description here

Columns are the following ['tave', 'tmax', 'tmin', 'vp', 'rhmax', 'rhmin', 'pp', 'gust']
So there are 365 measures of 'tave' during the year.
I want to add new column called 'next day tave' in the beginning of df.

How to do it?

My attempt is the following:

# let's add new column with "next day tave"
# "next day tave" is the value of next day
# e.g row 0, tave=-13.535, next tave=-5.791
 
next_tave_val = df.values[1:, 0:1]
print(next_tave_val.shape)
(364, 1)

# "next day tave" is 364 and we want to add that column to df that is 365 rows
# so need to add one more value to make it 365
# to append as 2d array

next_tave_val = np.append(next_tave_val, [[0]], axis=0)
print(next_tave_val.shape)

# now let's add 'next tave' column to df

df = df.insert(0,'next tave', next_tave_val)
print(df.shape)

Returns an error:

AttributeError: 'NoneType' object has no attribute 'shape'

What did I do wrong?

Upvotes: 1

Views: 1762

Answers (1)

user17242583
user17242583

Reputation:

There's actually a function designed for this very purpose: shift:

df['next day tave'] = df['tave'].shift(1)

Upvotes: 3

Related Questions