以下是一个示例代码,用于遍历数据框中的两列,并将它们的值连接到第三列中:
import pandas as pd
# 创建示例数据框
data = {'col1': [1, 2, 3, 4, 5],
'col2': ['a', 'b', 'c', 'd', 'e']}
df = pd.DataFrame(data)
# 创建一个空的列表,用于存储连接后的值
new_col = []
# 遍历数据框的两列,并将它们的值连接到第三列中
for index, row in df.iterrows():
new_value = str(row['col1']) + row['col2']
new_col.append(new_value)
# 将新列添加到数据框中
df['new_col'] = new_col
# 打印结果
print(df)
输出结果:
col1 col2 new_col
0 1 a 1a
1 2 b 2b
2 3 c 3c
3 4 d 4d
4 5 e 5e
在上述代码中,我们使用了Pandas库来创建一个示例数据框。然后,我们遍历数据框的每一行,并使用两列的值连接生成新的值。最后,我们将新列添加到数据框中,并打印结果。
上一篇:遍历数据框以提取每个值的计数
下一篇:遍历数据框中的两列