python中使用iterrows()对dataframe进行遍历的实例

  • Post category:Python

使用iterrows()方法对dataframe进行遍历是在处理数据的过程中比较常见的方式之一。下面是一个完整的攻略和两个示例:

攻略

Step 1: 导入必要的库

在使用itererrows()方法前,需要先导入pandas库:

import pandas as pd

Step 2: 构建数据

接着,我们需要构建一个数据集以便于进行遍历。这里我们采用一个包含几个城市、州和人口数量的简单数据集:

data = {
    'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix'],
    'State': ['NY', 'CA', 'IL', 'TX', 'AZ'],
    'Population': [8.6, 4.0, 2.7, 2.3, 1.7]
}

df = pd.DataFrame(data)

Step 3: 使用iterrows()方法进行遍历

现在,我们可以使用iterrows()方法对dataframe进行遍历了。iterrows()方法可以将每一行转换为一个元组,其中包含着该行的索引和数据。通过遍历这些元组,我们可以得到每一行的具体信息。

for index, row in df.iterrows():
    print(index)
    print(row['City'])
    print(row['State'])
    print(row['Population'])
    print('---------------')

以上代码中,我们使用了iterrows()方法对dataframe进行了遍历,最终输出结果如下:

0
New York
NY
8.6
---------------
1
Los Angeles
CA
4.0
---------------
2
Chicago
IL
2.7
---------------
3
Houston
TX
2.3
---------------
4
Phoenix
AZ
1.7
---------------

上述代码中,我们可以看到iterrows()方法将每一行数据都转换成了元组,而for循环则遍历了这些元组并输出了每一行的具体信息。

示例

我们再来看看两个具体的实例,更好地理解如何使用iterrows()方法进行遍历。

示例1: 计算每个城市的人口数的平方

for index, row in df.iterrows():
    population = row['Population']
    square = population ** 2
    print("The population square of {} is {}".format(row['City'], square))

输出结果如下:

The population square of New York is 73.96
The population square of Los Angeles is 16.0
The population square of Chicago is 7.290000000000001
The population square of Houston is 5.289999999999999
The population square of Phoenix is 2.8899999999999997

以上代码中,我们遍历了dataframe中的每一行数据,并根据人口数量计算了每个城市的人口数的平方,并输出了结果。

示例2: 修改每个城市的人口数量

for index, row in df.iterrows():
    df.at[index, 'Population'] = row['Population'] * 10000

print(df)

输出结果如下:

         City State  Population
0    New York    NY     86000.0
1  Los Angeles    CA     40000.0
2     Chicago    IL     27000.0
3     Houston    TX     23000.0
4     Phoenix    AZ     17000.0

以上代码中,我们遍历了dataframe中的每一行数据,并将每个城市的人口数量都乘以10000,从而实现了对每个城市的人口数量进行修改的功能。