python pandas 遍历 DataFrame

python pandas 遍历 DataFrame

df = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
                   'B': ['B0', 'B1', 'B2', 'B3'],
                   'C': ['C0', 'C1', 'C2', 'C3'],
                   'D': ['D0', 'D1', 'D2', 'D3']},
                  index=[0, 1, 2, 3])
df

python pandas 遍历 DataFrame_第1张图片

for index, row in df.iterrows(): # 按行遍历
    print("index:", index)
    print("--------------")
    print("row:", row)
    print("--------------")

Output exceeds the size limit. Open the full output data in a text editor

index: 0
--------------
row: A    A0
B    B0
C    C0
D    D0
Name: 0, dtype: object
--------------
index: 1
--------------
row: A    A1
B    B1
C    C1
D    D1
Name: 1, dtype: object
--------------
index: 2
--------------
row: A    A2
B    B2
C    C2
D    D2
Name: 2, dtype: object
--------------
index: 3
B    B3
C    C3
D    D3
Name: 3, dtype: object
--------------
for index, column in df.iteritems():  # 按列遍历
    print("index:", index)
    print("--------------")  
    print("column:", column)
    print("--------------")
Output exceeds the size limit. Open the full output data in a text editor

index: A
--------------
column: 0    A0
1    A1
2    A2
3    A3
Name: A, dtype: object
--------------
index: B
--------------
column: 0    B0
1    B1
2    B2
3    B3
Name: B, dtype: object
--------------
index: C
--------------
column: 0    C0
1    C1
2    C2
3    C3
Name: C, dtype: object
--------------
index: D
1    D1
2    D2
3    D3
Name: D, dtype: object
--------------
for row in df.itertuples():
    print(row) # 输出每一行
Pandas(Index=0, A='A0', B='B0', C='C0', D='D0')
Pandas(Index=1, A='A1', B='B1', C='C1', D='D1')
Pandas(Index=2, A='A2', B='B2', C='C2', D='D2')
Pandas(Index=3, A='A3', B='B3', C='C3', D='D3')
for column in df.iteritems():
    print(column) # 输出各列
('A', 0    A0
1    A1
2    A2
3    A3
Name: A, dtype: object)
('B', 0    B0
1    B1
2    B2
3    B3
Name: B, dtype: object)
('C', 0    C0
1    C1
2    C2
3    C3
Name: C, dtype: object)
('D', 0    D0
1    D1
2    D2
3    D3
Name: D, dtype: object)

(‘C’, 0 C0
1 C1
2 C2
3 C3
Name: C, dtype: object)
(‘D’, 0 D0
1 D1
2 D2
3 D3
Name: D, dtype: object)


你可能感兴趣的:(python,开发语言,后端)