pandas将多列拼接成一个新列
时间: 2023-07-13 10:27:53 浏览: 191
你可以使用 Pandas 的 `apply` 方法和 `lambda` 函数来将多列拼接成一个新列。
下面是一个示例代码,假设你有一个名为 `df` 的 DataFrame,其中包含 `col1`、`col2` 和 `col3` 三列,你想将它们拼接成一个名为 `new_col` 的新列:
```python
import pandas as pd
# 创建示例 DataFrame
df = pd.DataFrame({'col1': ['A', 'B', 'C'],
'col2': ['D', 'E', 'F'],
'col3': ['G', 'H', 'I']})
# 将三列拼接成一个新列
df['new_col'] = df.apply(lambda row: ''.join(row[['col1', 'col2', 'col3']].values), axis=1)
# 显示结果
print(df)
```
输出结果为:
```
col1 col2 col3 new_col
0 A D G ADG
1 B E H BEH
2 C F I CFI
```
在 `apply` 方法中,`axis=1` 参数表示对每一行执行函数,而 `lambda` 函数中的 `row[['col1', 'col2', 'col3']]` 表示选取当前行的 `col1`、`col2` 和 `col3` 三列,并将它们转换成一个列表;`''.join()` 方法将这个列表中的所有元素拼接成一个字符串,最终返回的结果就是新列的值。
阅读全文
相关推荐


















