Výběr dat v pandas

Python pro uživatele R

Daniel Chen

Instructor

Ruční vytvoření DataFrame

df = pd.DataFrame({
            'A': [1, 2, 3],
            'B': [4, 5, 6], 
            'C': [7, 8, 9]}, 
            index = ['x', 'y', 'z'])

print(df)
    A     B     C
x     1     4     7
y     2     5     8
z     3     6     9
Python pro uživatele R
df = pd.DataFrame({
 'A': [1, 2, 3],
 'B': [4, 5, 6], 
 'C': [7, 8, 9]}, 
 index = ['x', 'y', 'z'])
df
   A  B  C
x  1  4  7
y  2  5  8
z  3  6  9
df['A']
x    1
y    2
z    3
Name: A, dtype: int64
df.A
x    1
y    2
z    3
Name: A, dtype: int64
df[['A', 'B']]
   A  B
x  1  4
y  2  5
z  3  6
Python pro uživatele R

Výběr řádků

  • Popisek řádku (loc) vs. index řádku (iloc)
  • Python počítá od 0
Python pro uživatele R

Výběr řádků .iloc

df
   A  B  C
x  1  4  7
y  2  5  8
z  3  6  9
df.iloc[0]
A    1
B    4
C    7
Name: x, dtype: int64
df.iloc[[0, 1]]
   A  B  C
x  1  4  7
y  2  5  8
df.iloc[0, :]
A    1
B    4
C    7
Name: x, dtype: int64
df.iloc[[0, 1], :]
   A  B  C
x  1  4  7
y  2  5  8
Python pro uživatele R

Výběr řádků .loc

df
   A  B  C
x  1  4  7
y  2  5  8
z  3  6  9
df.loc['x']
A    1
B    4
C    7
Name: x, dtype: int64
df.loc[['x', 'y']]
   A  B  C
x  1  4  7
y  2  5  8
Python pro uživatele R
df
   A  B  C
x  1  4  7
y  2  5  8
z  3  6  9
df.loc['x', 'A']
1
df.loc[['x', 'y'], ['A', 'B']]
   A  B
x  1  4
y  2  5
Python pro uživatele R

Podmíněný výběr

df[df.A == 3]
   A  B  C
z  3  6  9
df[(df.A == 3) | (df.B == 4)]
   A  B  C
x  1  4  7
z  3  6  9
Python pro uživatele R

Atributy

df.shape
(3, 2)
df.shape()
 --------------------------------------------------------------------
TypeError                          Traceback (most recent call last)
<ipython-input-17-0e566b70f572> in <module>()
<hr />-> 1 df.shape()

TypeError: 'tuple' object is not callable
Python pro uživatele R

Lass uns üben!

Python pro uživatele R

Preparing Video For Download...