繁体   English   中英

如何在 dataframe 上使用 apply function 来检索特定列?

[英]How to use the apply function on a dataframe for retrieving a particular column?

我编写了以下代码用于下载数据集并在 DataFrame 上应用 EDA 功能

url = "https://query1.finance.yahoo.com/v7/finance/download/RELIANCE.BO?period1=1577110559&period2=1608732959&interval=1d&events=history&includeAdjustedClose=true"
r = requests.get(url)
open(stock+'.csv','wb').write(r.content)  
ril = pd.read_csv(r'RELIANCE.csv',date_parser='Date')
ril.head(10)

在这里,我想通过应用列检索Close列,以便使用df.apply() function 进行练习

def close(stock):
    print(stock.iloc[:,6])
ril.apply(close)

但是代码给出了IndexingError作为

IndexingError                             Traceback (most recent call last)
<ipython-input-21-9fad7d447930> in <module>()
----> 1 asp.apply(close)

7 frames
/usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py in _has_valid_tuple(self, key)
    698         for i, k in enumerate(key):
    699             if i >= self.ndim:
--> 700                 raise IndexingError("Too many indexers")
    701             try:
    702                 self._validate_key(k, i)

IndexingError: Too many indexers

可以用df.apply() function 来完成吗?

df = pd.read_csv(r'RELIANCE.csv',date_parser='Date')

close1 = df['Close']                                 #standard way of assessing the column
close2 = df.apply(lambda x: x.iloc[4] , axis=1)      #apply function row-wise: take 1
close3 = df.apply(lambda x: x[4]      , axis=1)      # ... take 2
close4 = df.apply(lambda x: x['Close'], axis=1)      # ... take 3

print( np.allclose(close1, close2, equal_nan=True) ) # verify
...

参考: pandas.DataFrame.ilocpandas.ZBA834BA059A9A379459C1112E4Z5。

基本上,在您的情况下发生的事情是您使用pd.apply以及索引df.iloc[:,...]迭代了 dataframe 。 注意axis=1 ,以便逐行应用 function

暂无
暂无

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

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