在 pandas 選取資料

給 R 使用者的 Python

Daniel Chen

Instructor

手動建立 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
給 R 使用者的 Python
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
給 R 使用者的 Python

列子集

  • 列標籤(loc)vs. 列索引(iloc
  • Python 從 0 開始計數
給 R 使用者的 Python

使用 .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
給 R 使用者的 Python

使用 .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
給 R 使用者的 Python
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
給 R 使用者的 Python

條件式篩選

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
給 R 使用者的 Python

屬性

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
給 R 使用者的 Python

一起來練習吧!

給 R 使用者的 Python

Preparing Video For Download...