在Python Pandas数据帧中的字符串和整数列中的项目周围添加单引号



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

我尝试了多个关于堆栈溢出的建议,使用 numpy 的 savetxt 方法使用 for 循环。(我不需要使用 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 和人员保持不变。列id_with_quotes、person_with_quotes是 id 和 person,每个项目都用单引号括起来。

您可以使用

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'
如果我

没看错你的问题,你可以做这样的事情。基本上遍历每一列,并在列中每个项目的开头和结尾添加引号。为了安全起见,在这两种情况下都转换为str

import pandas as pd
data = {"id": [101, 102, 103, 104, 105],
    "person": ['Ty', 'Al', 'Lou', 'Tao', 'Mick']}
df = pd.DataFrame(data)
df['id_w_quotes'] = df['id'].apply(lambda x: "'" + str(x) + "'")
df['person_w_quotes'] = df['person'].apply(lambda x: "'" + str(x) + "'")
df.head()

这给出了这个输出

    id  person id_w_quotes  person_w_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'

最新更新