Python、pandas 数据框行

问题描述 投票:0回答:1

我正在尝试迭代数据框的每一行。但是,在 B 列(逗号分隔字段)上使用行会将其拆分为单个字符。

A 栏 B 栏
宠物。 狗,猫

我正在使用的代码:

for index, row in df.iterrows():
    A1 = row['Column A']
    A2 = row['Column B']
    print(A2)
    A3 = add_units['Column A'].str.split(',').tolist()
    A4 = list(A3)
    A5 = json.dumps(A4)
    print(A5)

我尝试过列表和 json 转储,打印后格式看起来正确。但随后我无法迭代并使错误列表索引超出范围。

python pandas dataframe
1个回答
0
投票
import pandas as pd
import json

# Example DataFrame
data = {'Column A': ['pet', 'animal'], 'Column B': ['dog,cat', 'bird,fish']}
df = pd.DataFrame(data)

# Iterating through each row
for index, row in df.iterrows():
    A1 = row['Column A']
    A2 = row['Column B']
    
    # Splitting the comma-separated values in Column B
    A3 = A2.split(',')  # Directly split the row's value of Column B
    A5 = json.dumps(A3)
    print(A5)
    
    # Example of processing each item in A3
    for item in A3:
        print(f"Processing {item} in context of {A1}")
© www.soinside.com 2019 - 2024. All rights reserved.