首页 > 解决方案 > 在 Python Pandas 数据框中的字符串和整数列中的项目周围添加单引号

问题描述

我需要在 pandas 数据框中的 2 个不同列的每个项目周围添加单引号。一列具有整数值,另一列具有字符串值。然后我想将带有单引号的项目放入一个新列中。

我使用带有 numpy 的 savetxt 方法的 for 循环尝试了有关 stackoverflow 的多个建议。(我不需要使用 numpy)我尝试了正则表达式。无法让它完全正常工作。

import pandas as pd
import numpy as np
data = {"id": [101, 102, 103, 104, 105],
        "person": ['Ty', 'Al', 'Lou', 'Tao', 'Mick']}
df = pd.DataFrame(data)
id_in_quotes=[] #Wanted to put the new items with single quotes into an empty list and put into a new column
person_in_quotes=[] #Wanted to put the new items with single quotes into an empty list and put into a new column
for x in df: #DOES NOT WORK
   np.savetxt('text.txt',x, fmt='%r') #DOES NOT WORK
   x.append(id_in_quotes)#DOES NOT WORK

最后,想看4列:id、person、id_with_quotes、person_with_quotes。列 id 和 person 保持不变。列 id_with_quotes、person_with_quotes 是 id 和 person,每个项目都用单引号括起来。

标签: python-3.xpandas

解决方案


您可以使用以下方法实现此DataFrame.applymap目的DataFrame.merge

df_new = (df.merge(
            df.astype(str).applymap(lambda x: "'" + x + "'"),
            left_index=True, right_index=True,
            suffixes=('', '_with_quotes')))

print(df_new)

    id person id_with_quotes person_with_quotes
0  101     Ty          '101'               'Ty'
1  102     Al          '102'               'Al'
2  103    Lou          '103'              'Lou'
3  104    Tao          '104'              'Tao'
4  105   Mick          '105'             'Mick'

推荐阅读