简体   繁体   English

如何将列向量添加到数据框(Python、Pandas)

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

I have a df with 365 rows × 8 columns .我有一个 df 365 rows × 8 columns

在此处输入图像描述

Columns are the following ['tave', 'tmax', 'tmin', 'vp', 'rhmax', 'rhmin', 'pp', 'gust']列如下['tave', 'tmax', 'tmin', 'vp', 'rhmax', 'rhmin', 'pp', 'gust']
So there are 365 measures of 'tave' during the year.因此,一年中有 365 个'tave'
I want to add new column called 'next day tave' in the beginning of df.我想在 df 的开头添加名为'next day tave'的新列。

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?我做错了什么?

There's actually a function designed for this very purpose: shift :实际上有一个 function 专为此目的而设计: shift

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 else if 逻辑将条件列添加到 Pandas 数据框 - Python - Add conditional column to Pandas Data Frame using else if logic - Python 将数字序列添加到 Python 中 pandas 数据帧中的列 - add a sequence of numbers to a column in pandas data frame in Python python pandas 在 groupby 中应用 function,并将结果添加为数据框中的列 - python pandas apply function in groupby, and add results as column in data frame 如何将用户输入的数据添加到 pandas 数据框列? - How to add data entered by the user to a pandas data frame column? Python Pandas:如何在groupby / transform操作中向数据框添加一个全新的列 - Python Pandas: how to add a totally new column to a data frame inside of a groupby/transform operation 如何在不使用 Pandas 数据框的情况下将列名添加到 ipysheet? - How to add column names to ipysheet without using pandas data frame? 如何根据其他行值添加 pandas 数据框列 - How to add pandas data frame column based on other rows values 如何将列的一部分添加到新的 Pandas 数据框中? - How can I add parts of a column to a new pandas data frame? 如何向具有不同列号的 Pandas 数据框添加新行? - How to add new rows to a Pandas Data Frame with varying column numbers? 如何将 91 添加到 pandas 数据帧的列中的所有值? - How to add 91 to all the values in a column of a pandas data frame?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM