要遍历一个pandas DataFrame并创建一个新的DataFrame,可以使用iterrows()方法。下面是一个示例代码:
import pandas as pd
# 创建原始DataFrame
data = {'Name': ['Tom', 'Nick', 'John'],
'Age': [28, 32, 25],
'City': ['New York', 'Paris', 'London']}
df = pd.DataFrame(data)
# 创建新的空DataFrame
new_df = pd.DataFrame(columns=['Name', 'City', 'Status'])
# 遍历原始DataFrame并创建新的DataFrame
for index, row in df.iterrows():
name = row['Name']
city = row['City']
status = 'Active' if row['Age'] > 30 else 'Inactive'
new_df = new_df.append({'Name': name, 'City': city, 'Status': status}, ignore_index=True)
# 打印新的DataFrame
print(new_df)
这将输出一个新的DataFrame,其中包含根据条件创建的新列"Status"。