NAT624, Del 3: Recap av indeksering, laste inn data, figurer og feilmeldinger

Recap etter Del 1 og 2: Hva har vi egentlig gått gjennom til nå ?


Indeksering i 1D og 2D:

Rader og kolonner skilles med komma, mens kolon brukes til å angi mange rader/kolonner på en gang.

In [1]:
import numpy as np
In [2]:
arr=np.array([[2,45,6,34], [7,4,12,76], [3,5,0,13]])
arr, arr.shape
Out[2]:
(array([[ 2, 45,  6, 34],
        [ 7,  4, 12, 76],
        [ 3,  5,  0, 13]]),
 (3, 4))

Finn dette i arr:

  • Første element?
  • Første rad?
  • Tredje kolonne?
  • Første tre kolonner i to siste rader?
In [3]:
arr[0,0], arr[0,:], arr[:,2], 
arr[1:, :3]
Out[3]:
array([[ 7,  4, 12],
       [ 3,  5,  0]])

Bruke funksjoner:

Husk at brakkeparantes brukes for indeksering, mens vanlig parantes brukes til funksjoner.

In [4]:
# Gjennomsnitt av hele "arr"
np.mean(arr)
Out[4]:
17.25
In [5]:
# Gjennomsnitt av første rad 
np.mean(arr[0,:])
Out[5]:
21.75
In [6]:
# Gjennomsnitt av rad nr 2 og 3, kolonne nr 1. 
np.mean(arr[1:,:2])
Out[6]:
4.75

Laste inn data og lagre dataene til variabler

In [7]:
import sys
# Bytt ut stien under slik at den peker på hvor på din PC du har 
# lagret mappen "Funksjoner".
sys.path.append(r"W:\Work\Documents\EkteData\EkteData\Funksjoner")
from EkteDataFunk import loadData # for filinnlasting
In [8]:
file='TempBergenYearlyNonan.txt'
data = loadData(file, rydd='N')
data.shape, data  
Out[8]:
((160, 2),
 array([[1861.        ,    8.33636364],
        [1862.        ,    7.71666667],
        [1863.        ,    7.75833333],
        [1864.        ,    6.86666667],
        [1865.        ,    7.225     ],
        [1866.        ,    7.41666667],
        [1867.        ,    6.55      ],
        [1868.        ,    7.975     ],
        [1869.        ,    6.45      ],
        [1870.        ,    6.575     ],
        [1871.        ,    7.64545455],
        [1872.        ,    8.275     ],
        [1873.        ,    7.83333333],
        [1874.        ,    7.175     ],
        [1875.        ,    7.01666667],
        [1876.        ,    6.78333333],
        [1877.        ,    6.55      ],
        [1878.        ,    7.06666667],
        [1879.        ,    6.69166667],
        [1880.        ,    7.53333333],
        [1881.        ,    6.36666667],
        [1882.        ,    7.9       ],
        [1883.        ,    7.6       ],
        [1884.        ,    8.20833333],
        [1885.        ,    6.70833333],
        [1886.        ,    6.83333333],
        [1887.        ,    6.99166667],
        [1888.        ,    6.55      ],
        [1889.        ,    7.925     ],
        [1890.        ,    7.78333333],
        [1891.        ,    7.73333333],
        [1892.        ,    6.26666667],
        [1893.        ,    7.49166667],
        [1894.        ,    8.33333333],
        [1895.        ,    6.75833333],
        [1896.        ,    7.40833333],
        [1897.        ,    7.25      ],
        [1898.        ,    7.15      ],
        [1899.        ,    6.96666667],
        [1900.        ,    6.70833333],
        [1901.        ,    7.675     ],
        [1902.        ,    6.40833333],
        [1903.        ,    7.18333333],
        [1904.        ,    6.89166667],
        [1905.        ,    7.08333333],
        [1906.        ,    7.38333333],
        [1907.        ,    6.95      ],
        [1908.        ,    7.575     ],
        [1909.        ,    6.53333333],
        [1910.        ,    7.79166667],
        [1911.        ,    7.56666667],
        [1912.        ,    7.59166667],
        [1913.        ,    7.81666667],
        [1914.        ,    7.93333333],
        [1915.        ,    5.95833333],
        [1916.        ,    7.1       ],
        [1917.        ,    6.60833333],
        [1918.        ,    7.5       ],
        [1919.        ,    6.125     ],
        [1920.        ,    7.68333333],
        [1921.        ,    7.2       ],
        [1922.        ,    6.425     ],
        [1923.        ,    6.46666667],
        [1924.        ,    7.28333333],
        [1925.        ,    7.85833333],
        [1926.        ,    7.73333333],
        [1927.        ,    7.19166667],
        [1928.        ,    7.14166667],
        [1929.        ,    7.04166667],
        [1930.        ,    8.50833333],
        [1931.        ,    6.70833333],
        [1932.        ,    7.58333333],
        [1933.        ,    8.25833333],
        [1934.        ,    8.55833333],
        [1935.        ,    7.69166667],
        [1936.        ,    8.275     ],
        [1937.        ,    7.98333333],
        [1938.        ,    8.30833333],
        [1939.        ,    8.23333333],
        [1940.        ,    7.10833333],
        [1941.        ,    6.975     ],
        [1942.        ,    6.475     ],
        [1943.        ,    8.2       ],
        [1944.        ,    7.75833333],
        [1945.        ,    8.275     ],
        [1946.        ,    7.93333333],
        [1947.        ,    7.94166667],
        [1948.        ,    8.15833333],
        [1949.        ,    8.125     ],
        [1950.        ,    8.275     ],
        [1951.        ,    7.6       ],
        [1952.        ,    7.125     ],
        [1953.        ,    8.625     ],
        [1954.        ,    7.70833333],
        [1955.        ,    7.3       ],
        [1956.        ,    7.225     ],
        [1957.        ,    7.93333333],
        [1958.        ,    7.4       ],
        [1959.        ,    8.56666667],
        [1960.        ,    8.18333333],
        [1961.        ,    8.25833333],
        [1962.        ,    7.01666667],
        [1963.        ,    7.23333333],
        [1964.        ,    7.525     ],
        [1965.        ,    7.25      ],
        [1966.        ,    6.90833333],
        [1967.        ,    7.725     ],
        [1968.        ,    7.48333333],
        [1969.        ,    7.4       ],
        [1970.        ,    7.09166667],
        [1971.        ,    7.775     ],
        [1972.        ,    7.83333333],
        [1973.        ,    7.39166667],
        [1974.        ,    8.59166667],
        [1975.        ,    8.20833333],
        [1976.        ,    7.5       ],
        [1977.        ,    7.46666667],
        [1978.        ,    7.36666667],
        [1979.        ,    6.40833333],
        [1980.        ,    7.675     ],
        [1981.        ,    6.9       ],
        [1982.        ,    8.1       ],
        [1983.        ,    7.78333333],
        [1984.        ,    7.95833333],
        [1985.        ,    6.8       ],
        [1986.        ,    7.10833333],
        [1987.        ,    7.23333333],
        [1988.        ,    8.225     ],
        [1989.        ,    8.475     ],
        [1990.        ,    8.91666667],
        [1991.        ,    8.15833333],
        [1992.        ,    8.53333333],
        [1993.        ,    7.56666667],
        [1994.        ,    7.675     ],
        [1995.        ,    7.75      ],
        [1996.        ,    7.16666667],
        [1997.        ,    8.59166667],
        [1998.        ,    7.975     ],
        [1999.        ,    8.575     ],
        [2000.        ,    8.81666667],
        [2001.        ,    7.68333333],
        [2002.        ,    8.71666667],
        [2003.        ,    8.73333333],
        [2004.        ,    8.55      ],
        [2005.        ,    8.4       ],
        [2006.        ,    9.31666667],
        [2007.        ,    8.4       ],
        [2008.        ,    8.875     ],
        [2009.        ,    8.6       ],
        [2010.        ,    6.36666667],
        [2011.        ,    8.78333333],
        [2012.        ,    7.83333333],
        [2013.        ,    7.96666667],
        [2014.        ,    9.90833333],
        [2015.        ,    8.73333333],
        [2016.        ,    8.6       ],
        [2017.        ,    8.625     ],
        [2018.        ,    8.69166667],
        [2019.        ,    8.83333333],
        [2020.        ,    9.43333333]]))
In [9]:
tid=data[:,0]
temp=data[:,1]

Velge ut en spesifikk tidsperiode

fra en tidsserie med årlig oppløsning.

In [10]:
np.where(tid==1862)
Out[10]:
(array([1], dtype=int64),)
In [11]:
tid[1]
Out[11]:
1862.0
In [12]:
np.where(tid==1873)
Out[12]:
(array([12], dtype=int64),)
In [13]:
tid[12]
Out[13]:
1873.0
In [14]:
np.where((tid>=1870) & (tid<=1893))
Out[14]:
(array([ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
        26, 27, 28, 29, 30, 31, 32], dtype=int64),)
In [15]:
tid[9:32+1]
Out[15]:
array([1870., 1871., 1872., 1873., 1874., 1875., 1876., 1877., 1878.,
       1879., 1880., 1881., 1882., 1883., 1884., 1885., 1886., 1887.,
       1888., 1889., 1890., 1891., 1892., 1893.])

Lage figurer

In [16]:
import matplotlib.pyplot as plt
In [17]:
plt.plot(tid, temp)
plt.title('Temperatur Bergen')
plt.xlabel('År')
plt.ylabel('Temperatur [\u2103]')
plt.show()

Plot et spesifikk tidsperiode

In [18]:
plt.plot(tid[1:12], temp[1:12])
plt.title('Temperatur Bergen')
plt.xlabel('År')
plt.ylabel('Temperatur [\u2103]')
plt.show()

Plot flere tidsserier:

  • hele tidsserien,
  • hver femte verdi,
  • verdiene fra indeks 50 til og med 149.
In [19]:
plt.plot(tid, temp)
plt.plot(tid[::5], temp[::5])
plt.plot(tid[50:150], temp[50:150])
plt.title('Temperatur Bergen')
plt.xlabel('År')
plt.ylabel('Temperatur [\u2103]')
plt.show()

Feilmeldinger

In [20]:
tid[2.0:4]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-1c9c600f1626> in <module>
----> 1 tid[2.0:4]

TypeError: slice indices must be integers or None or have an __index__ method
In [21]:
tid(2:4)
  File "<ipython-input-21-48780e612567>", line 1
    tid(2:4)
         ^
SyntaxError: invalid syntax
In [22]:
tid[2:4
  File "<ipython-input-22-c4e0309f63cc>", line 1
    tid[2:4
           ^
SyntaxError: unexpected EOF while parsing
In [23]:
plt.plot(tid[3:],temp[5:])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-23-a35341d92509> in <module>
----> 1 plt.plot(tid[3:],temp[5:])

~\Anaconda3\envs\EkteData\lib\site-packages\matplotlib\pyplot.py in plot(scalex, scaley, data, *args, **kwargs)
   2838 @_copy_docstring_and_deprecators(Axes.plot)
   2839 def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
-> 2840     return gca().plot(
   2841         *args, scalex=scalex, scaley=scaley,
   2842         **({"data": data} if data is not None else {}), **kwargs)

~\Anaconda3\envs\EkteData\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex, scaley, data, *args, **kwargs)
   1741         """
   1742         kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1743         lines = [*self._get_lines(*args, data=data, **kwargs)]
   1744         for line in lines:
   1745             self.add_line(line)

~\Anaconda3\envs\EkteData\lib\site-packages\matplotlib\axes\_base.py in __call__(self, data, *args, **kwargs)
    271                 this += args[0],
    272                 args = args[1:]
--> 273             yield from self._plot_args(this, kwargs)
    274 
    275     def get_next_color(self):

~\Anaconda3\envs\EkteData\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs)
    397 
    398         if x.shape[0] != y.shape[0]:
--> 399             raise ValueError(f"x and y must have same first dimension, but "
    400                              f"have shapes {x.shape} and {y.shape}")
    401         if x.ndim > 2 or y.ndim > 2:

ValueError: x and y must have same first dimension, but have shapes (157,) and (155,)
In [24]:
plt.plot(tid,temp)
plt.xlabel('tid)
plt.ylabel('temp')
plt.title('Årlig temperatur fra 1861 til 2020')
  File "<ipython-input-24-d21779473fb5>", line 2
    plt.xlabel('tid)
                    ^
SyntaxError: EOL while scanning string literal

Dele en tidserie inn i like lange bolker

In [25]:
ind=[
    0,
    len(tid)*1/4,
    len(tid)*2/4,
    len(tid)*3/4,
    len(tid)
]
In [26]:
ind
Out[26]:
[0, 40.0, 80.0, 120.0, 160]
In [27]:
ind=[
    0,
    int(len(tid)*1/4),
    int(len(tid)*2/4),
    int(len(tid)*3/4),
    len(tid)
]
ind
Out[27]:
[0, 40, 80, 120, 160]
In [28]:
plt.plot(tid[ind[0]:ind[1]], temp[ind[0]:ind[1]])
plt.plot(tid[ind[1]:ind[2]], temp[ind[1]:ind[2]])
plt.plot(tid[ind[2]:ind[3]], temp[ind[2]:ind[3]])
plt.plot(tid[ind[3]:ind[4]], temp[ind[3]:ind[4]])

plt.title('Temperatur Bergen')
plt.xlabel('År')
plt.ylabel('Temperatur [\u2103]')
plt.show()
In [ ]:
 

Last ned og prøv selv:

Åpne i github