【问题标题】:Convert A Column and Column B In Pandas to One Long String (Python 3)将 Pandas 中的 A 列和 B 列转换为一个长字符串(Python 3)
【发布时间】:2019-07-09 13:23:35
【问题描述】:
enter image description here如何将 pandas 的列转换为一个长字符串?
例如,转换以下DF:
column1 column2
John Noun
Went Verb
To DT[enter image description here][2]
Fetch Verb
His AD
Ball Noun
读作
关键字
John/Noun went/Verb to/DT fetch/Verb his/AD Ball/Noun
有什么帮助吗?
【问题讨论】:
标签:
python
python-3.x
string
pandas
【解决方案1】:
用分隔符连接列并调用join:
s = ' '.join(df['Keyword'] + '/' + df['Tag'])
或者使用str.cat:
s = ' '.join(df['Keyword'].str.cat(df['Tag'], sep='/'))
如果需要连接所有列,请使用apply:
s = ' '.join(df.apply( '/'.join, axis=1))
#if possible some non strings columns
#s = ' '.join(df.astype(str).apply( '/'.join, axis=1))
print (s)
John/Noun Went/Verb To/DT Fetch/Verb His/AD Ball/Noun To read/as