Python - Problemas al importar ficheros csv con series de tiempo

 
Vista:
sin imagen de perfil
Val: 24
Ha disminuido su posición en 3 puestos en Python (en relación al último mes)
Gráfica de Python

Problemas al importar ficheros csv con series de tiempo

Publicado por Enrique (13 intervenciones) el 23/12/2020 12:49:49
Los ficheros csv,importados de un Banco, tienen como características que los diferencia de los que descargo de Yahoo, las siguientes: decimal =",", sep='\t')) En el siguiente enlace, incluyo los ficheros necesarios para los scripts que comento a continuación.
https://drive.google.com/drive/folders/1q5XtNkM61RLqdmwH9W5vlq6Lcy0WPp4A

Con este srcipt, importo en un DataFrame las cotizaciones incluidas en éstos ficheros csv.# Importar ficheros csv descargados de Renta 4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import glob
import pandas as pd
import datetime as dt
 
# Dirección para obtener los ficheros
path = "/media/enri/Mi_Proyecto/Py_Proyecto_2020/Py_Paso_Peregrino/Ficheros_R4_csv/"
 
"""Importa los datos de los ficheros csv de una dirección determinada"""
filenames = glob.glob(path + "*.csv")
dfs = []
nombres = []
for filename in filenames:
    nombre = filename[len(path):-4]
    nombres.append(nombre)
    #dfs.append(pd.read_csv(filename, index_col = "Date", names = nombres))
    dfs.append( pd.read_csv(filename ,index_col = "Date",  decimal  =",", parse_dates = ["Date"],
                            na_values = ["nan"], sep='\t'))
dfs = iter(dfs)
df_R4 = next(dfs)
for df_ in dfs:
    df_R4 = df_R4.merge(df_, on='Date')
 
df_R4.columns = nombres
#df_R4.dropna(inplace = True)
 
df_R4

La información del df me indica que las fechas que constituyen el índice, no tienen dtype. Además su formato es 20/12/2013 , cuando yo deseo el formato 2000-1-4
A).- ¿Se pueden solucionar estos dos problemeas, directamente durante la importación?.

A continuación, con las siguientes sentencias, consigo dicho objetivo.

1
2
3
4
5
6
7
df_R4.reset_index(inplace = True)
 
df_R4['Date'] = pd.to_datetime(df_R4['Date'], errors='coerce')
#df_R4['Date'] = df_R4['Date'].dt.strftime('%d/%m/%Y')
 
df_R4 = df_R4.set_index("Date")
df_R4.info()

Pero, a continuación me encuentro con los siguientes problemas para manejar esta serie de tiempo como normalmente hago con otras importadas de Yahoo.

En estos casos que indico a continuación, me devuelve elerror:

1
2
3
4
# filtrando todo febrero de 2016
df_R4['2016-2']
# filtrando sólo del 2016-02-04 al 2016-02-18
df_R4['2016-02-04':'2016-02-18']
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-5-d8265c6c8c3c> in <module>
1 # filtrando todo febrero de 2016
----> 2 print(df_R4['2016-2'])
3 # filtrando sólo del 2016-02-04 al 2016-02-18
4 print(df_R4['2016-02-04':'2016-02-18'])

~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/frame.py in __getitem__(self, key)
2883 # either we have a slice or we have a string that can be converted
2884 # to a slice for partial-string date indexing
-> 2885 return self._slice(indexer, axis=0)
2886
2887 # Do we have a (boolean) DataFrame?

~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/generic.py in _slice(self, slobj, axis)
3555 Slicing with this method is *always* positional.
3556 """
-> 3557 assert isinstance(slobj, slice), type(slobj)
3558 axis = self._get_block_manager_axis(axis)
3559 result = self._constructor(self._mgr.get_slice(slobj, axis=axis))

AssertionError: <class 'numpy.ndarray'>

El índice, como he indicado, contiene fechas que estan ordenadas correlativamente. Pues bien, la siguiente sentencias

1
2
3
4
df_R4 = df_R4.dropna()
 
# Valores al cierre de cada mes.
df_R4.asfreq('M', method='ffill')

me devuelve el error

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-c5999c510a95> in <module>
2
3 # Valores al cierre de cada mes.
----> 4 df_R4.asfreq('M', method='ffill')

~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/generic.py in asfreq(self, freq, method, how, normalize, fill_value)
7539 from pandas.core.resample import asfreq
7540
-> 7541 return asfreq(
7542 self,
7543 freq,

~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/resample.py in asfreq(obj, freq, method, how, normalize, fill_value)
1875 dti = date_range(obj.index[0], obj.index[-1], freq=freq)
1876 dti.name = obj.index.name
-> 1877 new_obj = obj.reindex(dti, method=method, fill_value=fill_value)
1878 if normalize:
1879 new_obj.index = new_obj.index.normalize()

~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/util/_decorators.py in wrapper(*args, **kwargs)
307 @wraps(func)
308 def wrapper(*args, **kwargs) -> Callable[..., Any]:
--> 309 return func(*args, **kwargs)
310
311 kind = inspect.Parameter.POSITIONAL_OR_KEYWORD

~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/frame.py in reindex(self, *args, **kwargs)
4030 kwargs.pop("axis", None)
4031 kwargs.pop("labels", None)
-> 4032 return super().reindex(**kwargs)
4033
4034 def drop(

~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/generic.py in reindex(self, *args, **kwargs)
4459
4460 # perform the reindex on the axes
-> 4461 return self._reindex_axes(
4462 axes, level, limit, tolerance, method, fill_value, copy
4463 ).__finalize__(self, method="reindex")

~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/frame.py in _reindex_axes(self, axes, level, limit, tolerance, method, fill_value, copy)
3876 index = axes["index"]
3877 if index is not None:
-> 3878 frame = frame._reindex_index(
3879 index, method, copy, level, fill_value, limit, tolerance
3880 )

~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/frame.py in _reindex_index(self, new_index, method, copy, level, fill_value, limit, tolerance)
3892 tolerance=None,
3893 ):
-> 3894 new_index, indexer = self.index.reindex(
3895 new_index, method=method, level=level, limit=limit, tolerance=tolerance
3896 )

~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/indexes/base.py in reindex(self, target, method, level, limit, tolerance)
3332 # check is_overlapping for IntervalIndex compat
3333 if self.is_unique and not getattr(self, "is_overlapping", False):
-> 3334 indexer = self.get_indexer(
3335 target, method=method, limit=limit, tolerance=tolerance
3336 )

~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/indexes/base.py in get_indexer(self, target, method, limit, tolerance)
2989
2990 if method == "pad" or method == "backfill":
-> 2991 indexer = self._get_fill_indexer(target, method, limit, tolerance)
2992 elif method == "nearest":
2993 indexer = self._get_nearest_indexer(target, limit, tolerance)

~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/indexes/base.py in _get_fill_indexer(self, target, method, limit, tolerance)
3029 indexer = engine_method(target_values, limit)
3030 else:
-> 3031 indexer = self._get_fill_indexer_searchsorted(target, method, limit)
3032 if tolerance is not None:
3033 indexer = self._filter_indexer_tolerance(target_values, indexer, tolerance)

~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/indexes/base.py in _get_fill_indexer_searchsorted(self, target, method, limit)
3052 indexer = self.get_indexer(target)
3053 nonexact = indexer == -1
-> 3054 indexer[nonexact] = self._searchsorted_monotonic(target[nonexact], side)
3055 if side == "left":
3056 # searchsorted returns "indices into a sorted array such that,

~/anaconda3/envs/plotly/lib/python3.8/site-packages/pandas/core/indexes/base.py in _searchsorted_monotonic(self, label, side)
5045 return len(self) - pos
5046
-> 5047 raise ValueError("index must be monotonic increasing or decreasing")
5048
5049 def get_slice_bound(self, label, side: str_t, kind) -> int:

ValueError: index must be monotonic increasing or decreasing

Estoy desconcertado por que, necesito trabajar con ambos formatos csv. Agradeceré Sus sugerencias. Enlace para comproba que, con ficheros descargados de Yahoo, no sucede lo mismo introducir la descripción del enlace aquí

En los enlaces he incluido el notebook. Agradeceré su ayuda.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder