gpt4 book ai didi

python - 如何连接 Pandas 中的两个数据框?

转载 作者:太空宇宙 更新时间:2023-11-03 14:38:44 25 4
gpt4 key购买 nike

有两个数据框。

如何按元素拼接?

可以看到代码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?']]

最佳答案

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

关于python - 如何连接 Pandas 中的两个数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55185105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com