pandas DataFrame遍历

1、 使用迭代器遍历行 :iterrows

使用 iterrows() 方法可以遍历 DataFrame 的每一行,返回的是每一行的索引和数据的元组。

import pandas as pd

data = {'A': [1, 2, 3],
        'B': [4, 5, 6]}

df = pd.DataFrame(data)


for index, row in df.iterrows():
    print('index:', index)
    print('A:', row['A'])
    print('B:', row['B'])

index: 0
A: 1
B: 4
index: 1
A: 2
B: 5
index: 2
A: 3
B: 6

2、 使用apply() 函数遍历列

使用 apply() 函数可以遍历 DataFrame 的每一列,对每一列应用自定义函数。

import pandas as pd

data = {'A': [1, 2, 3],
        'B': [4, 5, 6]}

df = pd.DataFrame(data)
print(df)

   A  B
0  1  4
1  2  5
2  3  6


def custom_function(column):
    return column * 2

result_df = df.apply(custom_function)
print(result_df)

   A   B
0  2   8
1  4  10
2  6  12

传到custom_function函数中的column参数是一个元组,形式(0, 1) (1, 2) (2, 3)

  • 第一个元素是行索引
  • 第二个元素是value

3、 使用applymap() 遍历每个单元格

使用 applymap() 函数可以遍历 DataFrame 的每个单元格,对每个单元格应用自定义函数。

import pandas as pd

data = {'A': [1, 2, 3],
        'B': [4, 5, 6]}

df = pd.DataFrame(data)
print(df)

   A  B
0  1  4
1  2  5
2  3  6


def custom_function(cell):
    return cell * 2

result = df.applymap(custom_function)
print(result)

   A   B
0  2   8
1  4  10
2  6  12

传到custom_function函数中的cell参数是每一个value

4、 使用iteritems() 遍历列

使用 iteritems() 方法可以遍历 DataFrame 的每一列,返回的是列名和数据的 Series 对象。

import pandas as pd

data = {'A': [1, 2, 3],
        'B': [4, 5, 6]}

df = pd.DataFrame(data)

for column_name, column_data in df.iteritems():
    print(f'Column Name: {column_name}, Column Data: {column_data.tolist()}')

Column Name: A, Column Data: [1, 2, 3]
Column Name: B, Column Data: [4, 5, 6]

发表评论

评论列表,共 0 条评论

    暂无评论