Python Pandas - 迭代



在資料操作中,遍歷 pandas 物件是一項基本任務,遍歷的行為取決於您正在處理的物件型別。本教程解釋了 pandas 中的迭代是如何工作的,特別關注 Series 和 DataFrame 物件。

pandas 中的迭代行為在 Series 和 DataFrame 物件之間有所不同 -

  • Series:遍歷 Series 物件會直接產生值,使其類似於陣列結構。

  • DataFrame:遍歷 DataFrame 遵循類似字典的約定,其中迭代會產生列標籤(即鍵)。

遍歷 DataFrame 中的行

要遍歷 DataFrame 的行,我們可以使用以下方法 -

  • items():遍歷 (鍵,值) 對

  • iterrows():將行迭代為 (索引,系列) 對

  • itertuples():將行迭代為命名元組

遍歷列對

items() 方法允許您將每一列迭代為鍵值對,其中標籤作為鍵,列值作為 Series 物件。此方法與 DataFrame 的類似字典的介面一致。

示例

以下示例使用 items() 方法迭代 DataFrame 行。在此示例中,每列都作為 Series 中的鍵值對單獨迭代。

import pandas as pd
import numpy as np
 
df = pd.DataFrame(np.random.randn(4,3),columns=['col1','col2','col3'])

print("Original DataFrame:\n", df)

# Iterate Through DataFrame rows
print("Iterated Output:")
for key,value in df.items():
   print(key,value)

輸出如下 -

Original DataFrame:
        col1      col2      col3
0  0.422561  0.094621 -0.214307
1  0.430612 -0.334812 -0.010867
2  0.350962 -0.145470  0.988463
3  1.466426 -1.258297 -0.824569

Iterated Output:
col1 0    0.422561
1    0.430612
2    0.350962
3    1.466426
Name: col1, dtype: float64
col2 0    0.094621
1   -0.334812
2   -0.145470
3   -1.258297
Name: col2, dtype: float64
col3 0   -0.214307
1   -0.010867
2    0.988463
3   -0.824569
Name: col3, dtype: float64

觀察,每列都單獨迭代,其中鍵是列名,值是相應的 Series 物件。

將 DataFrame 迭代為 Series 對

iterrows() 方法返回一個迭代器,該迭代器會產生索引和行對,其中每一行都表示為 Series 物件,其中包含每一行中的資料。

示例

以下示例使用 iterrows() 方法迭代 DataFrame 行。

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(4,3),columns = ['col1','col2','col3'])

print("Original DataFrame:\n", df)

# Iterate Through DataFrame rows
print("Iterated Output:")
for row_index,row in df.iterrows():
   print(row_index,row)

輸出如下 -

Original DataFrame:
        col1      col2      col3
0  0.468160 -0.634193 -0.603612
1  1.231840  0.090565 -0.449989
2 -1.645371  0.032578 -0.165950
3  1.956370 -0.261995  2.168167

Iterated Output:
0 col1    0.468160
col2   -0.634193
col3   -0.603612
Name: 0, dtype: float64
1 col1    1.231840
col2    0.090565
col3   -0.449989
Name: 1, dtype: float64
2 col1   -1.645371
col2    0.032578
col3   -0.165950
Name: 2, dtype: float64
3 col1    1.956370
col2   -0.261995
col3    2.168167
Name: 3, dtype: float64

注意:因為 iterrows() 遍歷行,所以它不會在行之間保留資料型別。0、1、2 是行索引,col1、col2、col3 是列索引。

將 DataFrame 迭代為命名元組

itertuples() 方法將返回一個迭代器,為 DataFrame 中的每一行生成一個命名元組。元組的第一個元素將是行的對應索引值,其餘值為行值。此方法通常比 iterrows() 快,並保留行元素的資料型別。

示例

以下示例使用 itertuples() 方法將 DataFrame 行迴圈為命名元組

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(4,3),columns = ['col1','col2','col3'])

print("Original DataFrame:\n", df)

# Iterate Through DataFrame rows
print("Iterated Output:")
for row in df.itertuples():
   print(row)

輸出如下 -

Original DataFrame:
        col1      col2      col3
0  0.501238 -0.353269 -0.058190
1 -0.426044 -0.012733 -0.532594
2 -0.704042  2.201186 -1.960429
3  0.514151 -0.844160  0.508056

Iterated Output:
Pandas(Index=0, col1=0.5012381423628608, col2=-0.3532690739340918, col3=-0.058189913290578134)
Pandas(Index=1, col1=-0.42604395958954777, col2=-0.012733326002509393, col3=-0.5325942971498149)
Pandas(Index=2, col1=-0.7040424042099052, col2=2.201186165472291, col3=-1.9604285032438307)
Pandas(Index=3, col1=0.5141508750506754, col2=-0.8441600001815068, col3=0.5080555294913854)

遍歷 DataFrame 列

當您遍歷 DataFrame 時,它只會返回列名。

示例

讓我們考慮以下示例來了解 DataFrame 列的遍歷。

import pandas as pd
import numpy as np
 
N = 5
df = pd.DataFrame({
   'A': pd.date_range(start='2016-01-01', periods=N, freq='D'),
   'x': np.linspace(0, stop=N-1, num=N),
   'y': np.random.rand(N),
   'C': np.random.choice(['Low', 'Medium', 'High'], N).tolist(),
   'D': np.random.normal(100, 10, size=N).tolist()
})

print("Original DataFrame:\n", df)

# Iterate Through DataFrame Columns
print("Output:")
for col in df:
   print(col)

輸出如下 -

Original DataFrame:
            A    x         y     C           D
0 2016-01-01  0.0  0.990949   Low  114.143838
1 2016-01-02  1.0  0.314517  High   95.559640
2 2016-01-03  2.0  0.180237   Low  121.134817
3 2016-01-04  3.0  0.170095   Low   95.643132
4 2016-01-05  4.0  0.920718   Low   96.379692

Output:
A
x
y
C
D

示例

在遍歷 DataFrame 時,您不應該修改任何物件。迭代旨在用於讀取,迭代器返回原始物件的副本(檢視),這意味著更改不會反映在原始物件上。以下示例演示了上述語句。

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(4,3),columns = ['col1','col2','col3'])

for index, row in df.iterrows():
   row['a'] = 10
print(df)

輸出如下 -

        col1       col2       col3
0  -1.739815   0.735595  -0.295589
1   0.635485   0.106803   1.527922
2  -0.939064   0.547095   0.038585
3  -1.016509  -0.116580  -0.523158

如您所見,DataFrame 中沒有反映任何更改,因為迭代僅提供資料的檢視。

廣告