深度阅读

How to Iterate Over Columns in Pandas DataFrame

作者
作者
2023年08月22日
更新时间
10.52 分钟
阅读时间
0
阅读量

To iterate over columns in a Pandas DataFrame, you can use the iteritems() method. Here’s an example:

import pandas as pd

data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'Gender': ['F', 'M', 'M']
}

df = pd.DataFrame(data)

for column_name, column_data in df.iteritems():
    print(f"Column name: {column_name}")
    print(f"Column data:\n{column_data}\n")

In this example, df.iteritems() returns an iterator that yields two-tuples containing the column name as the first element and a pandas Series object containing the data in the column as the second element. The for loop iterates over the columns of the DataFrame, and the print() statements shows the name and data of each column.

Note that iterating over columns using iteritems() is rarely necessary in pandas. It’s usually better to use vectorized operations and built-in functions to manipulate the data in the DataFrame. However, in some cases iterating over columns can be useful for custom operations and other advanced use cases.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。