以下是一个示例代码,演示如何遍历DataFrame的每一行,并按照特定条件创建批处理。假设有一个DataFrame名为df,其中有两列,分别为"Name"和"Age":
import pandas as pd
# 创建一个空的DataFrame
batch_df = pd.DataFrame(columns=["Name", "Age"])
# 遍历DataFrame的每一行
for index, row in df.iterrows():
name = row["Name"]
age = row["Age"]
# 根据特定条件创建批处理
if age >= 18:
batch = f"Process {name} as an adult"
else:
batch = f"Process {name} as a minor"
# 将批处理添加到新的DataFrame中
batch_df = batch_df.append({"Name": name, "Age": age, "Batch": batch}, ignore_index=True)
# 打印新的DataFrame
print(batch_df)
在上述代码中,我们首先创建了一个空的DataFrame batch_df
,用于存储批处理的结果。然后,我们使用iterrows()
方法遍历了原始DataFrame df
的每一行,并提取了"Name"和"Age"列的值。
接下来,我们根据特定条件创建了批处理。在这个示例中,如果年龄大于等于18岁,则将其视为成年人,否则将其视为未成年人。
最后,我们使用append()
方法将每个批处理的结果添加到新的DataFrame batch_df
中,并打印出来。