在Pandas和GeoPandas中,可以使用几种不同的方法来遍历DataFrame的每一行
- import pandas as pd
-
-
- data = {
- 'column1': range(1, 1001),
- 'column2': range(1001, 2001)
- }
- df = pd.DataFrame(data)
- df

- for index, row in df.iterrows():
- print(index)
- print(row)
- '''
- 0
- column1 1
- column2 1001
- Name: 0, dtype: int64
- 1
- column1 2
- column2 1002
- Name: 1, dtype: int64
- 2
- column1 3
- column2 1003
- Name: 2, dtype: int64
- 3
- column1 4
- column2 1004
- Name: 3, dtype: int64
- ...
- '''
- for row in df.itertuples():
- print(row)
- print(row.Index)
- print(row.column1)
- print(row.column2)
- '''
- Pandas(Index=0, column1=1, column2=1001)
- 0
- 1
- 1001
- Pandas(Index=1, column1=2, column2=1002)
- 1
- 2
- 1002
- Pandas(Index=2, column1=3, column2=1003)
- 2
- 3
- 1003
- ...
- '''
iterrows() 快,因为它返回命名元组,遍历的是元组而不是Series对象。- def process_row(row):
- print(row)
-
- df.apply(process_row, axis=1)
- '''
- column1 1
- column2 1001
- Name: 0, dtype: int64
- column1 2
- column2 1002
- Name: 1, dtype: int64
- column1 3
- column2 1003
- Name: 2, dtype: int64
- ...
- '''
itertuples() 慢,而且在使用上可能比直接遍历更复杂一些。- def process_row(element):
- print(element)
-
- df.applymap(process_row)
- '''
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- ...
- '''
- for i in range(len(df)):
- print(df.at[i,'column1'],df.at[i,'column2'])
- '''
- 1 1001
- 2 1002
- 3 1003
- 4 1004
- 5 1005
- ...
- '''
python 笔记: timeit (测量代码运行时间)-CSDN博客zhiguan
- import timeit
- def row_at(df):
- for i in range(len(df)):
- df.at[i,'column1']
- df.at[i,'column2']
-
- def iter_row(df):
- for index,row in df.iterrows():
- index
- row
-
- def iter_tuple(df):
- for row in df.itertuples():
- row
-
- def apply_df(df):
- df.apply(lambda x:x,axis=1)
-
- def apply_map_df(df):
- df.applymap(lambda x:x)
-
- time_at=timeit.timeit("row_at(df)", globals=globals(),number=1000)
- time_iterrow=timeit.timeit('iter_row(df)',globals=globals(),number=1000)
- time_itertuple=timeit.timeit('iter_tuple(df)',globals=globals(),number=1000)
- time_apply=timeit.timeit('apply_df(df)',globals=globals(),number=1000)
- time_applymap=timeit.timeit('apply_map_df(df)',globals=globals(),number=1000)
-
- time_at,time_iterrow,time_itertuple,time_apply,time_applymap
- '''
- (4.100567077999585,
- 14.672198772001138,
- 0.37428459300281247,
- 12.572721185002592,
- 0.5845120449957903)
- '''
直观可视化
- import seaborn as sns
- import matplotlib.pyplot as plt
-
- x = ['at by row','iterrows','itertuples','apply','applymap']
- y = [time_at,time_iterrow,time_itertuple,time_apply,time_applymap] # 请将这些值替换为你实际的时间数据
-
- sns.barplot(x=x, y=y)
- # 创建 barplot
-
-
- for i, val in enumerate(y):
- plt.text(i, val + 0.01, round(val, 2), ha='center')
- # 添加标签(x轴、y轴、text的label)
-
- # 显示图形
- plt.show()
