0

Tengo una dataframe por lo cual quiero utilizar una funcion para cambiar ratio pero solo para lineas donde Country es ESP.

    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

Por eso intenté np.where:

np.where(df['Country'] == 'ESP', 
         df.apply(update_current_ratio_US), 
         df['ratio'])

Pero me devuelve:

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'

La funcion es:

def update_current_ratio_US(row):
    print(row)
    name = row['Ticker']
    if row['ratio'] == None:
        bs = requests.get(f'https://financialmodelingprep.com/api/v3/financials/balance-sheet-statement/{ticker}?period=quarter')
        bs = bs.json()
        try:
            total_assets = bs.get("financials")[0].get("Total assets")
            total_liabilities = bs.get("financials")[0].get('Total liabilities')
            try:
                ratio = float(total_assets)/float(total_liabilities)
                return ratio
            except ZeroDivisionError:
                print("ZeroDivisionError, total_liabilities: ", ticker, " ", total_liabilities)
            except ValueError:
                print("ValueError, total_assets", total_assets, " total_liabilities", total_liabilities)
        except TypeError:
            print("ticker: ", ticker)
            pass # here we will try with webscrapping

1 respuesta 1

0

En vez de usar numpy.where puedes usar simplemente un filtro boleano con pandas.DataFrame.loc.

Por otro lado la variable ticker no la defines en la función, en todo caso defines nombre.

Por último no debes retornar ratio, debes asignar el valor a la serie y retornarla siempre (se modifique o no el valor).

import io
import requests
import pandas as pd


data = io.StringIO("""\
Ticker,Name,Exchange,Category Name,Country,ratio,earnings
AAPL,Apple Inc.,NMS,Electronic Equipment,USA,NaN,NaN
BAC,Bank of America Corporation,NYQ,Money Center Banks,USA,NaN,NaN
AMZN,Amazon.com Inc.,NMS,Catalog & Mail Order Houses,USA,NaN,NaN
T,AT&T Inc.,NYQ,Telecom Services - Domestic,USA,NaN,NaN
GOOG,Alphabet Inc.,NMS,Internet Information Providers,ESP,NaN,NaN
""")

def update_current_ratio_US(row):
    ticker = row['Ticker']
    if pd.isnull(row['ratio']):
        bs = requests.get(f'https://financialmodelingprep.com/api/v3/financials/balance-sheet-statement/{ticker}?period=quarter')
        bs = bs.json()
        try:
            total_assets = bs.get("financials")[0].get("Total assets")
            total_liabilities = bs.get("financials")[0].get('Total liabilities')
            try:
                ratio = float(total_assets) / float(total_liabilities)
            except ZeroDivisionError:
                print(f"ZeroDivisionError, total_liabilities: {ticker} {total_liabilities}")
            except ValueError:
                print(f"ValueError, total_assets {total_assets}, total_liabilities, {total_liabilities}")
            else:
                row["ratio"] = ratio
        except TypeError:
            print(f"ticker: {ticker}")
            pass # here we will try with webscrapping
    return row


df = pd.read_csv(data)

rows = df['Country'] == 'ESP'
df.loc[rows] =  df.loc[rows].apply(update_current_ratio_US, axis=1)
>>> df
  Ticker                         Name Exchange  \
0   AAPL                   Apple Inc.      NMS   
1    BAC  Bank of America Corporation      NYQ   
2   AMZN              Amazon.com Inc.      NMS   
3      T                    AT&T Inc.      NYQ   
4   GOOG                Alphabet Inc.      NMS   

                    Category Name Country     ratio  earnings  
0            Electronic Equipment     USA       NaN       NaN  
1              Money Center Banks     USA       NaN       NaN  
2     Catalog & Mail Order Houses     USA       NaN       NaN  
3     Telecom Services - Domestic     USA       NaN       NaN  
4  Internet Information Providers     ESP  3.864032       NaN

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.