Python:3.8.5
pandas:1.1.3
按列遍历DataFrame:
测试用例:
import pandas as pd
test = pd.DataFrame(columns = ['first', 'second', 'third'])
for i in range(10):
test.loc[i] = [i, i + 1, i + 2]
#-------------------------------------------------------
''' 测试用例
first second third
0 0 1 2
1 1 2 3
2 2 3 4
3 3 4 5
4 4 5 6
5 5 6 7
6 6 7 8
7 7 8 9
8 8 9 10
'''
以(index, Series)对的形式迭代DataFrame行。
for index, row in test.iterrows():
print(index) # 输出每一行的索引
此处的index数据类型为 int
此处的row数据类型为 pandas.core.series.Series
for index, row in test.iterrows():
print(row['first'], row['third']) # 输出每一行的'first'与'second'的值
此处的row['first']数据类型为 int
for row in test.iterrows():
print(row) # 输出所有数据
此处的row数据类型为 tuple
循环中可以通过 _‘变量名[‘列名’]’_的形式访问每一行中的对应列的值
以命名元组的形式遍历DataFrame行。
for row in test.itertuples():
print(getattr(row, 'Index')) # 输出每一行的索引
此处的getattr(row, 'Index')数据类型 int
此处的row数据类型为 pandas.core.frame.Pandas
for row in test.itertuples():
print(getattr(row, 'first'), getattr(row, 'third')) # 输出每一行的'first'与'third'的值
此处的getattr(row, 'first')数据类型为 int
此处的row数据类型为 pandas.core.frame.Pandas
遍历DataFrame列,返回一个具有列名和内容为Series的元组。
for columnName, column in test.items():
print(columnName) # 输出列名,这里是输出 'first', 'second', 'third'
此处的columnName的数据类型为 str
for i, column in test.items():
print(column) # 输出每一列的元素,每一列都是一个Series的对象
此处的column的数据类型为 pandas.core.series.Series
for i, column in test.items():
print(column[2:7]) # 输出每一列第2到第6个数据
此处column[x:y]的数据类型为 pandas.core.series.Series
遍历DataFrame列,返回一个具有列名和内容为Series的元组。
for name, column in test.iteritems():
print(i) # 输出列名
#此处的name数据类型为 str
for name, column in test.iteritems():
print(column[1]) # 输出第一行的数据
#此处column[x]的数据类型为 int
for name, column in test.iteritems():
print(column[2:7]) # 输出每一列第2到第6个数据
#此处column[x:y]的数据类型为 pandas.core.series.Series
Original: https://blog.csdn.net/nailnehc/article/details/117386397
Author: nailnehc
Title: pandas.DataFrame 按行和列遍历DataFrame
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/676275/
转载文章受原作者版权保护。转载请注明原作者出处!