python - 连接列中的单词
问题描述
背景
我有以下代码
import pandas as pd
#create df
df = pd.DataFrame({'Before' : ['there are many different',
'i like a lot of sports ',
'the middle east has many '],
'After' : ['in the bright blue box',
'because they go really fast ',
'to ride and have fun '],
'P_ID': [1,2,3],
'Word' : ['crayons', 'cars', 'camels'],
'N_ID' : ['A1', 'A2', 'A3']
})
#rearrange
df = df[['P_ID', 'N_ID', 'Before', 'Word','After']]
它创建了以下内容df
P_ID N_ID Before Words After
0 1 A1 there are many different crayons in the bright blue box
1 2 A2 i like a lot of sports cars because they go really fast
2 3 A3 the middle east has many camels to ride and have fun
目标
1)将和列中的单词Before
与列中的单词连接起来After
Word
2) 创建一个new_column
期望的输出
A new_column
具有以下输出
new_column
there are many different crayons in the bright blue box
i like a lot of sports cars because they go really fast
the middle east has many camels to ride and have fun
问题
我如何实现我的目标?
解决方案
您只需添加这些列:
df['new_column'] = df['Before'] + ' ' + df['Word'] + ' ' + df['After']
这是完整的代码:
import pandas as pd
#create df
df = pd.DataFrame({'Before' : ['there are many different',
'i like a lot of sports ',
'the middle east has many '],
'After' : ['in the bright blue box',
'because they go really fast ',
'to ride and have fun '],
'P_ID': [1,2,3],
'Word' : ['crayons', 'cars', 'camels'],
'N_ID' : ['A1', 'A2', 'A3']
})
#rearrange
df = df[['P_ID', 'N_ID', 'Word', 'Before', 'After']]
df['new_column'] = df['Before'] + ' ' + df['Word'] + ' ' + df['After']
df['new_column']
0 there are many different crayons in the bright... 1 i like a lot of sports cars because they go r... 2 the middle east has many camels to ride and h... Name: new_column, dtype: object
推荐阅读
- php - 如何在codeigniter的一个功能控制器中调用2个模型功能
- azure - Azure B2C 自定义策略:不安全的 RestfulProvider
- security - 易受 SQL 注入攻击
- node.js - 将包含对象和数组的项目发布到 Mongo - 数组不发布数据
- github - PR 的 Github 文件更改通知
- linux - 如何使用 U 盘作为构建目录来使用 cmake 编译 OpenCV?
- sql - 父子层次结构中缺少路径
- bootstrap-4 - bootstrap 4如何添加顶部标题和底部标题
- mysql - 我无法使用 JAX-RS 处理异常
- python - 在加载的 csv 的“n”位置添加一行