Python 如何在pandas中串接多个字符串列?
我想将数据帧中的两行连接成一行。我当前的代码:Python 如何在pandas中串接多个字符串列?,python,dataframe,Python,Dataframe,我想将数据帧中的两行连接成一行。我当前的代码: import pandas as pd df = pd.DataFrame(columns = ['string1', 'string2']) df.loc[len(df), :] = ['Hello', 'This is Sam'] df.loc[len(df), :] = ['how are you?', 'from Canada'] #create the next row: ['Hello how are you?', 'This is
import pandas as pd
df = pd.DataFrame(columns = ['string1', 'string2'])
df.loc[len(df), :] = ['Hello', 'This is Sam']
df.loc[len(df), :] = ['how are you?', 'from Canada']
#create the next row: ['Hello how are you?', 'This is Sam from Canada']
怎么做
您可以测试代码。将
agg
与append
一起使用:
df = df.append(df.agg(' '.join), ignore_index=True)
df
string1 string2
0 Hello This is Sam
1 how are you? from Canada
2 Hello how are you? This is Sam from Canada
您好,请发布一些示例数据以及结果应该是什么样子您问的是“如何连接行…”,但您真正的意思是“如何连接多个文本列…”,因为您希望在行1和行2之间连接
string1
列,例如“这是Sam”+“来自加拿大”。这是连接列而不是行,这是字符串连接(将多个字符串连接为一个字符串,而不是通常将多个行连接为一个包含多行的数据帧)。