简体   繁体   English

如何连接pandas中的两个数据帧?

[英]How to concatenate two dataframes in pandas?

There are two dataframes. 有两个数据帧。

How to concatenate element-wise? 如何连接元素?

You can see the code 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?']]

If the index and columns are the same, use any of the following DataFrame string concatenation operations. 如果索引和列相同,请使用以下任何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?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM