Este es un ejemplo de clase sobre la manipulación de archivos csv usando python
In [ ]:
lll
kkk
In [1]:
help(open)
Help on built-in function open in module io:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a stream. Raise IOError upon failure.
file is either a text or byte string giving the name (and the path
if the file isn't in the current working directory) of the file to
be opened or an integer file descriptor of the file to be
wrapped. (If a file descriptor is given, it is closed when the
returned I/O object is closed, unless closefd is set to False.)
mode is an optional string that specifies the mode in which the file
is opened. It defaults to 'r' which means open for reading in text
mode. Other common values are 'w' for writing (truncating the file if
it already exists), 'x' for creating and writing to a new file, and
'a' for appending (which on some Unix systems, means that all writes
append to the end of the file regardless of the current seek position).
In text mode, if encoding is not specified the encoding used is platform
dependent: locale.getpreferredencoding(False) is called to get the
current locale encoding. (For reading and writing raw bytes use binary
mode and leave encoding unspecified.) The available modes are:
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
========= ===============================================================
The default mode is 'rt' (open for reading text). For binary random
access, the mode 'w+b' opens and truncates the file to 0 bytes, while
'r+b' opens the file without truncation. The 'x' mode implies 'w' and
raises an `FileExistsError` if the file already exists.
Python distinguishes between files opened in binary and text modes,
even when the underlying operating system doesn't. Files opened in
binary mode (appending 'b' to the mode argument) return contents as
bytes objects without any decoding. In text mode (the default, or when
't' is appended to the mode argument), the contents of the file are
returned as strings, the bytes having been first decoded using a
platform-dependent encoding or using the specified encoding if given.
'U' mode is deprecated and will raise an exception in future versions
of Python. It has no effect in Python 3. Use newline to control
universal newlines mode.
buffering is an optional integer used to set the buffering policy.
Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
line buffering (only usable in text mode), and an integer > 1 to indicate
the size of a fixed-size chunk buffer. When no buffering argument is
given, the default buffering policy works as follows:
* Binary files are buffered in fixed-size chunks; the size of the buffer
is chosen using a heuristic trying to determine the underlying device's
"block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
On many systems, the buffer will typically be 4096 or 8192 bytes long.
* "Interactive" text files (files for which isatty() returns True)
use line buffering. Other text files use the policy described above
for binary files.
encoding is the name of the encoding used to decode or encode the
file. This should only be used in text mode. The default encoding is
platform dependent, but any encoding supported by Python can be
passed. See the codecs module for the list of supported encodings.
errors is an optional string that specifies how encoding errors are to
be handled---this argument should not be used in binary mode. Pass
'strict' to raise a ValueError exception if there is an encoding error
(the default of None has the same effect), or pass 'ignore' to ignore
errors. (Note that ignoring encoding errors can lead to data loss.)
See the documentation for codecs.register or run 'help(codecs.Codec)'
for a list of the permitted encoding error strings.
newline controls how universal newlines works (it only applies to text
mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
follows:
* On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.
* On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '' or '\n', no translation takes place. If newline is any
of the other legal values, any '\n' characters written are translated
to the given string.
If closefd is False, the underlying file descriptor will be kept open
when the file is closed. This does not work when a file name is given
and must be True in that case.
A custom opener can be used by passing a callable as *opener*. The
underlying file descriptor for the file object is then obtained by
calling *opener* with (*file*, *flags*). *opener* must return an open
file descriptor (passing os.open as *opener* results in functionality
similar to passing None).
open() returns a file object whose type depends on the mode, and
through which the standard file operations such as reading and writing
are performed. When open() is used to open a file in a text mode ('w',
'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
a file in a binary mode, the returned class varies: in read binary
mode, it returns a BufferedReader; in write binary and append binary
modes, it returns a BufferedWriter, and in read/write mode, it returns
a BufferedRandom.
It is also possible to use a string or bytearray as a file for both
reading and writing. For strings StringIO can be used like a file
opened in a text mode, and for bytes a BytesIO can be used like a file
opened in a binary mode.
In [ ]:
# %load demo.txt
ste es un demo que me permite la transformacion de datos
por medio de los conocimientos adquiridos en el diplomado
In [ ]:
# %load demo1.txt
hola
este es un documento
In [12]:
%%writefile demo2.txt
linea 1
linea 2
linea 3
linea 4
Writing demo2.txt
In [96]:
import pandas as pd
import statistics
import numpy as np
In [35]:
# skiprows para saltar columnas al leer
x=pd.read_csv('AportesDiario_2004.csv', sep=';',decimal=',',thousands='.',skiprows=2)
In [33]:
x.head()
Out[33]:
Fecha
Region Hidrologica
Nombre Rio
Aportes Caudal m3/s
Aportes Energia kWh
Aportes %
mes
0
1/01/2004
ANTIOQUIA
A. SAN LORENZO
17.56
3910000.0
72,27%
NaN
1
1/01/2004
ANTIOQUIA
CONCEPCION
6.15
1385300.0
123,69%
NaN
2
1/01/2004
ANTIOQUIA
DESV. EEPPM (NEC,PAJ,DOL)
11.43
2574700.0
147,13%
NaN
3
1/01/2004
ANTIOQUIA
GRANDE
18.65
4563500.0
79,23%
NaN
4
1/01/2004
ANTIOQUIA
GUADALUPE
11.28
2540900.0
80,15%
NaN
In [32]:
x['Fecha']
Out[32]:
0 1/01/2004
1 1/01/2004
2 1/01/2004
3 1/01/2004
4 1/01/2004
5 1/01/2004
6 1/01/2004
7 1/01/2004
8 1/01/2004
9 1/01/2004
10 1/01/2004
11 1/01/2004
12 1/01/2004
13 1/01/2004
14 1/01/2004
15 1/01/2004
16 1/01/2004
17 1/01/2004
18 1/01/2004
19 1/01/2004
20 1/01/2004
21 1/01/2004
22 1/01/2004
23 1/01/2004
24 2/01/2004
25 2/01/2004
26 2/01/2004
27 2/01/2004
28 2/01/2004
29 2/01/2004
...
8754 30/12/2004
8755 30/12/2004
8756 30/12/2004
8757 30/12/2004
8758 30/12/2004
8759 30/12/2004
8760 31/12/2004
8761 31/12/2004
8762 31/12/2004
8763 31/12/2004
8764 31/12/2004
8765 31/12/2004
8766 31/12/2004
8767 31/12/2004
8768 31/12/2004
8769 31/12/2004
8770 31/12/2004
8771 31/12/2004
8772 31/12/2004
8773 31/12/2004
8774 31/12/2004
8775 31/12/2004
8776 31/12/2004
8777 31/12/2004
8778 31/12/2004
8779 31/12/2004
8780 31/12/2004
8781 31/12/2004
8782 31/12/2004
8783 31/12/2004
Name: Fecha, dtype: object
In [41]:
# x['Region Hidrologica'] == 'ANTIOQUIA' es una condicion y devuelve falsos y verdaderos y cuando hago
#x[x['Region Hidrologica'] == 'ANTIOQUIA'] me devuelve los elementos que cumplen la condición
filtro=x[x['Region Hidrologica'] == 'ANTIOQUIA']
In [42]:
len(filtro)
Out[42]:
4026
In [43]:
# Set conjunto de datos que no estan repetidos
set(x['Nombre Rio'])
Out[43]:
{'A. SAN LORENZO',
'ALTOANCHICAYA',
'BATA',
'BOGOTA N.R.',
'CALIMA',
'CAUCA SALVAJINA',
'CHUZA',
'CONCEPCION',
'DESV. EEPPM (NEC,PAJ,DOL)',
'DIGUA',
'FLORIDA II',
'GRANDE',
'GUADALUPE',
'GUATAPE',
'GUAVIO',
'MAGDALENA BETANIA',
'MIEL I',
'NARE',
'OTROS RIOS (ESTIMADOS)',
'PORCE II',
'PRADO',
'SAN CARLOS',
'SINU URRA',
'TENCHE'}
In [44]:
# A cada cambio en nombre rio (los agrupa con groupby) calculeme la media de las columnas numericas
x.groupby('Nombre Rio').mean()
Out[44]:
Aportes Caudal m3/s
Aportes Energia kWh
mes
Nombre Rio
A. SAN LORENZO
36.466612
8.105400e+06
NaN
ALTOANCHICAYA
43.468716
4.620596e+06
NaN
BATA
95.478989
1.571243e+07
NaN
BOGOTA N.R.
28.051803
1.277674e+07
NaN
CALIMA
11.922077
5.560117e+05
NaN
CAUCA SALVAJINA
113.523306
2.519614e+06
NaN
CHUZA
9.742486
4.337967e+06
NaN
CONCEPCION
6.606667
1.488170e+06
NaN
DESV. EEPPM (NEC,PAJ,DOL)
8.312240
2.291866e+06
NaN
DIGUA
27.529536
4.299954e+05
NaN
FLORIDA II
10.712486
2.148367e+05
NaN
GRANDE
27.511967
6.729973e+06
NaN
GUADALUPE
20.167978
4.542911e+06
NaN
GUATAPE
34.103033
5.624479e+06
NaN
GUAVIO
85.884563
2.062469e+07
NaN
MAGDALENA BETANIA
374.490765
5.580630e+06
NaN
MIEL I
78.433251
3.430428e+06
NaN
NARE
49.711612
1.738808e+07
NaN
OTROS RIOS (ESTIMADOS)
NaN
3.700457e+06
NaN
PORCE II
99.292650
4.976887e+06
NaN
PRADO
45.597268
4.984191e+05
NaN
SAN CARLOS
24.910492
3.084509e+06
NaN
SINU URRA
284.444208
3.165074e+06
NaN
TENCHE
3.900874
8.786683e+05
NaN
In [47]:
n=set(x['Nombre Rio'])
In [97]:
rio=[]
media=[]
for y in n:
z=x[x['Nombre Rio'] == y]['Aportes Energia kWh'] # para cada linea que cumpla la condicion de tener el mismo nobre de rio
# traigolos aportes de energia
rio.append(y)
if len(z) > 0:
print(y, statistics.mean(z.values[:]))
media2= np.array(media.append(statistics.mean(z.values[:])))
NARE 17388083.6066
TENCHE 878668.306011
GUAVIO 20624689.3443
MIEL I 3430428.4153
SINU URRA 3165074.04372
PRADO 498419.125683
FLORIDA II nan
SAN CARLOS 3084508.74317
ALTOANCHICAYA 4620595.90164
GUATAPE 5624479.23497
DESV. EEPPM (NEC,PAJ,DOL) nan
A. SAN LORENZO 8105399.72678
CHUZA nan
OTROS RIOS (ESTIMADOS) 3700456.8306
CALIMA 556011.748634
CAUCA SALVAJINA 2519614.48087
CONCEPCION 1488170.4918
GRANDE 6729973.22404
BATA 15712428.4153
BOGOTA N.R. nan
DIGUA 429995.355191
GUADALUPE 4542910.92896
PORCE II 4976887.15847
MAGDALENA BETANIA 5580630.32787
In [99]:
resultado=pd.DataFrame(data=media2,index=rio)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-99-55300f1bdaa4> in <module>()
----> 1 resultado=pd.DataFrame(data=media2,index=rio)
C:\Users\USUARIO\Anaconda3\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy)
253 else:
254 mgr = self._init_ndarray(data, index, columns, dtype=dtype,
--> 255 copy=copy)
256 elif isinstance(data, (list, types.GeneratorType)):
257 if isinstance(data, types.GeneratorType):
C:\Users\USUARIO\Anaconda3\lib\site-packages\pandas\core\frame.py in _init_ndarray(self, values, index, columns, dtype, copy)
410 # by definition an array here
411 # the dtypes will be coerced to a single dtype
--> 412 values = _prep_ndarray(values, copy=copy)
413
414 if dtype is not None:
C:\Users\USUARIO\Anaconda3\lib\site-packages\pandas\core\frame.py in _prep_ndarray(values, copy)
5323 values = values.reshape((values.shape[0], 1))
5324 elif values.ndim != 2:
-> 5325 raise ValueError('Must pass 2-d input')
5326
5327 return values
ValueError: Must pass 2-d input
In [93]:
resultado
Out[93]:
0
NARE
1.738808e+07
TENCHE
8.786683e+05
GUAVIO
2.062469e+07
MIEL I
3.430428e+06
SINU URRA
3.165074e+06
PRADO
4.984191e+05
FLORIDA II
NaN
SAN CARLOS
3.084509e+06
ALTOANCHICAYA
4.620596e+06
GUATAPE
5.624479e+06
DESV. EEPPM (NEC,PAJ,DOL)
NaN
A. SAN LORENZO
8.105400e+06
CHUZA
NaN
OTROS RIOS (ESTIMADOS)
3.700457e+06
CALIMA
5.560117e+05
CAUCA SALVAJINA
2.519614e+06
CONCEPCION
1.488170e+06
GRANDE
6.729973e+06
BATA
1.571243e+07
BOGOTA N.R.
NaN
DIGUA
4.299954e+05
GUADALUPE
4.542911e+06
PORCE II
4.976887e+06
MAGDALENA BETANIA
5.580630e+06
In [ ]:
Content source: ikvergarab/DiplomadoOLADE
Similar notebooks: