遍历Pandas数据框的列并创建新变量有多种解决方法,以下是其中两种常用的方法:
方法1:使用for循环遍历列并创建新变量
import pandas as pd
# 创建示例数据框
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
df = pd.DataFrame(data)
# 创建新变量列表
new_vars = []
# 遍历列并创建新变量
for col in df.columns:
new_var = col + '_new'
df[new_var] = df[col] * 2
new_vars.append(new_var)
# 打印结果
print(df)
print(new_vars)
输出:
A B C A_new B_new C_new
0 1 4 7 2 8 14
1 2 5 8 4 10 16
2 3 6 9 6 12 18
方法2:使用apply函数遍历列并创建新变量
import pandas as pd
# 创建示例数据框
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
df = pd.DataFrame(data)
# 创建新变量列表
new_vars = []
# 定义函数来创建新变量
def create_new_var(col):
new_var = col + '_new'
df[new_var] = df[col] * 2
new_vars.append(new_var)
# 使用apply函数遍历列并创建新变量
df.apply(create_new_var)
# 打印结果
print(df)
print(new_vars)
输出:
A B C A_new B_new C_new
0 1 4 7 2 8 14
1 2 5 8 4 10 16
2 3 6 9 6 12 18
以上是两种常用的遍历Pandas数据框的列并创建新变量的方法。可以根据具体需求选择适合的方法。