简体   繁体   English

如何从 Pandas 向子数据框添加新列

[英]How to add a new column to a sub-dataframe from pandas

I am starting to work with pandas, so this is probably a pretty obvious question, but I have been struggling with it for a while now and found no solution.我开始使用熊猫,所以这可能是一个非常明显的问题,但我已经为此苦苦挣扎了一段时间,但没有找到解决方案。

Consider this dataframe:考虑这个数据框:

import pandas_datareader as pdr
apple = pdr.DataReader('AAPL', data_source='yahoo', 
                      start=datetime.datetime(2013, 1, 1), 
                      end=datetime.datetime(2020, 1, 1))

Now, I can add a new column to this dataframe simply doing:现在,我可以简单地向这个数据框添加一个新列:

apple['new_column'] = np.arange(apple.shape[0])

However, if I usse iloc to extract a subdataframe and try to add a new column to the subdataframe:但是,如果我使用iloc提取子数据框并尝试向子数据框添加新列:

apple_2 = apple.iloc[1:5,:]
apple_2['test2'] = np.arange(4)

I get the error message:我收到错误消息:

<stdin>:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

What am I doing wrong and how am I supposed to do this in pandas?我做错了什么,我应该如何在熊猫中做到这一点? The error suggests using .loc but I do not know how to use it to add new columns.该错误建议使用.loc但我不知道如何使用它来添加新列。

You can do:你可以做:

apple_2 = apple.loc[:, 'High':'Close']

this will give you all the columns between 'High' and ' Close' (without close).这将为您提供“高”和“关闭”(不关闭)之间的所有列。 But there are also other ways to column-slice a dataframe.但是还有其他方法可以对数据帧进行列切片。 You an check this question .你一个检查这个问题

EDIT:编辑:

apple_2 = apple.loc[:, 'High':'Close']
#add a new column to apple_2
apple_2['new_column'] = np.arange(apple_2.shape[0]) 

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM