如何在熊猫中串联两个数据框?

时间:2019-03-15 14:43:14

标签: python dataframe

有两个数据框。

如何按元素连接?

您可以看到代码here

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?']]

1 个答案:

答案 0 :(得分:4)

如果索引和列相同,请使用以下任何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?