小编nel*_*c77的帖子

如何将元组连接到 Pandas 数据框中的字符串?

我正在尝试将元组连接到 pandas 数据框的一列中,并将该字符串放置在一个新的单独列中。

例如:

df = pd.DataFrame({'Number': ['001', '002', '003'],
                   'Tuple': [('hey', 'you'), ('you', 'can'), ('can', 'go')]})
Run Code Online (Sandbox Code Playgroud)

我已经使用以下方法测试了连接:

' '.join(_df.Tuple[0])
Run Code Online (Sandbox Code Playgroud)

输出如下:

'hey you';

Tuple但是,当我尝试使用以下命令将其扩展到数据框中的其余列时:

df['String'] = ' '.join([entry for entry in df.Tuple])
Run Code Online (Sandbox Code Playgroud)

我收到类型错误:TypeError: sequence item 0: expected str instance, tuple found。当我查看此错误时,我看到一个适用于列表但不适用于数据帧的示例。如何迭代数据框,连接每行中的元组并将这些字符串放入新列中?

python tuples pandas

4
推荐指数
1
解决办法
2616
查看次数

标签 统计

pandas ×1

python ×1

tuples ×1