python - 如何在熊猫中连接两个数据框?
问题描述
有两个数据框。
如何按元素连接?
你可以在这里看到代码
df1 = pd.DataFrame(columns = ['string1', 'string2'])
df1.loc[len(df1), :] = ['Hello', 'This is Sam']
df1.loc[len(df1), :] = ['Good?', 'Are you free']
df2 = pd.DataFrame(columns = ['string1', 'string2'])
df2.loc[len(df2), :] = ['how are you?', 'from Canada']
df2.loc[len(df2), :] = ['morning', 'to have a talk?']
df1
string1 string2
0 Hello This is Sam
1 Good? Are you free
df2
string1 string2
0 how are you? from Canada
1 morning to have a talk?
#How to get the desired dataframe: [['Hello how are you?', 'This is Sam from Canada'], ['Good morning?', 'Are you free to have a talk?']]
解决方案
如果索引和列相同,请使用以下任一 DataFrame 字符串连接操作。
df1 + ' ' + df2
string1 string2
0 Hello how are you? This is Sam from Canada
1 Good? morning Are you free to have a talk?
df1.add(' ').add(df2)
string1 string2
0 Hello how are you? This is Sam from Canada
1 Good? morning Are you free to have a talk?
df2.radd(df1.add(' '))
string1 string2
0 Hello how are you? This is Sam from Canada
1 Good? morning Are you free to have a talk?
推荐阅读
- reactjs - rxjs 可观察捕获错误上缺少“body”属性
- lua - “内存分配错误:块太大”做简单的整数除法
- ngx-admin - ngx-admin 卡片填充和边距
- terraform - 我们如何从 terraform gcp 资源 iam 绑定中的变量添加项目编号
- python - 通过阈值使用通用句子编码器的句子相似度
- ruby-on-rails - 即使禁用缓存,Rails 仍会缓存视图/控制器
- c# - C# 解析 JSON 对象
- verilog - 使用 yosys-smtbmc 证明时是否可以使用 $display 打印一些值?
- node.js - 也找不到名称空间“NodeJS”与类型节点
- list - 访问列表从一个飞镖飘到另一个飞镖