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

nel*_*c77 4 python tuples 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。当我查看此错误时,我看到一个适用于列表但不适用于数据帧的示例。如何迭代数据框,连接每行中的元组并将这些字符串放入新列中?

Dat*_*ice 5

它不起作用的原因是因为您的列表理解返回不可变的元组:

([entry for entry in df.Tuple])

回报

[('hey', 'you'), ('you', 'can'), ('can', 'go')]
Run Code Online (Sandbox Code Playgroud)

一种更简单的方法是在行级别上对元组中的每个项目使用聚合方法。

df['Tuple'].agg(' '.join)

out:
0    hey you
1    you can
2     can go
Name: Tuple, dtype: object
Run Code Online (Sandbox Code Playgroud)

  • 来自OP方法:`df.Tuple = [''.join(entry) for Entry in df.Tuple]`(作为OP的注释) (2认同)
  • 在之前添加 `fillna(' ')` 或过滤掉 NA 行@nellac77 (2认同)