Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在列中仅在某些行中应用pandas函数,但使用整行作为参数_Python_Python 3.x_Pandas_Function_Dataframe - Fatal编程技术网

Python 在列中仅在某些行中应用pandas函数,但使用整行作为参数

Python 在列中仅在某些行中应用pandas函数,但使用整行作为参数,python,python-3.x,pandas,function,dataframe,Python,Python 3.x,Pandas,Function,Dataframe,我有一个数据帧,我想使用一个函数来更改比率,但仅适用于国家为美国的行 Ticker Name Exchange Category Name Country ratio earnings 0 AAPL Apple Inc. NMS Electronic Equipment USA NaN NaN 1 BAC Bank of America Corporation NYQ Money Cent

我有一个数据帧,我想使用一个函数来更改
比率
,但仅适用于国家为
美国
的行

    Ticker  Name    Exchange    Category Name   Country     ratio   earnings
0   AAPL    Apple Inc.  NMS     Electronic Equipment    USA     NaN     NaN
1   BAC     Bank of America Corporation     NYQ     Money Center Banks  USA     NaN     NaN
2   AMZN    Amazon.com, Inc.    NMS     Catalog & Mail Order Houses     USA     NaN     NaN
3   T   AT&T Inc.   NYQ     Telecom Services - Domestic     USA     NaN     NaN
4   GOOG    Alphabet Inc.   NMS     Internet Information Providers  ESP     NaN     NaN
然而,我的函数使用了行中的一些东西来给出一个比率,一个结果

因此,我尝试使用np。其中:

np.where(df['Country'] == 'US', 
         df.apply(update_current_ratio_US), 
         df['ratio'])
但它的回报是:

0                 AAPL
1                  BAC
2                 AMZN
3                    T
4                 GOOG
             ...      
20723            2GB.F
20724            A7A.F
20725             GROG
20726    INDSWFTLTD.NS
20727           N1H.AX
Name: Ticker, Length: 20728, dtype: object

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-93-065d34d423e5> in <module>
      1 np.where(df['Country'] == 'USA', 
----> 2          df.apply(update_current_ratio_US),
      3          df['ratio'])

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, raw, result_type, args, **kwds)
   6876             kwds=kwds,
   6877         )
-> 6878         return op.get_result()
   6879 
   6880     def applymap(self, func) -> "DataFrame":

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\apply.py in get_result(self)
    184             return self.apply_raw()
    185 
--> 186         return self.apply_standard()
    187 
    188     def apply_empty_result(self):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_standard(self)
    294             try:
    295                 result = libreduction.compute_reduction(
--> 296                     values, self.f, axis=self.axis, dummy=dummy, labels=labels
    297                 )
    298             except ValueError as err:

pandas\_libs\reduction.pyx in pandas._libs.reduction.compute_reduction()

pandas\_libs\reduction.pyx in pandas._libs.reduction.Reducer.get_result()

<ipython-input-92-8243964de6d7> in update_current_ratio_US(row)
      1 def update_current_ratio_US(row):
      2     print(row)
----> 3     name = row['Ticker']
      4     if row['ratio'] == None:
      5         bs = requests.get(f'https://financialmodelingprep.com/api/v3/financials/balance-sheet-statement/{ticker}?period=quarter')

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    869         key = com.apply_if_callable(key, self)
    870         try:
--> 871             result = self.index.get_value(self, key)
    872 
    873             if not is_scalar(result):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key)
   4403         k = self._convert_scalar_indexer(k, kind="getitem")
   4404         try:
-> 4405             return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
   4406         except KeyError as e1:
   4407             if len(self) > 0 and (self.holds_integer() or self.is_boolean()):

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()

KeyError: 'Ticker'
更新 与:

看来我能得到结果:

array([nan, nan, nan, ..., 0.09515716983227814, 0.48105283873873134,
       1.0239341871349645], dtype=object)

但是您知道如何将它们保存在相应的行中吗?

我认为您需要在
apply
中指定axis=1。当在数据帧上使用时,请尝试
df.apply(update\u current\u ratio\u US,axis=1)
@Ben.T,谢谢。我想就是这样。你知道我如何将结果保存在相应的行中吗?如果你想将其设置回列定量,那么
df['ration']=np.where(…blablabla)
?@Ben.T该死,我以为会更复杂。类似于
df.loc[df['Country']='USA']['ratio']=np.where(…blabla)
thanki我认为您需要在
apply
中指定axis=1。在数据帧上使用时,尝试
df.apply(更新当前比率,axis=1)
@Ben.T,谢谢。我想就是这样。你知道我如何将结果保存在相应的行中吗?如果你想将其设置回列定量,那么
df['ration']=np.where(…blablabla)
?@Ben.T该死,我以为会更复杂。类似于
df.loc[df['Country']='USA']['ratio']=np.where(…blabla)
谢谢
np.where(df['Country'] == 'US', 
         df.apply(update_current_ratio_US, axis = 1), 
         df['ratio'])
    
array([nan, nan, nan, ..., 0.09515716983227814, 0.48105283873873134,
       1.0239341871349645], dtype=object)