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

2024-01-21

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

我在 stackoverflow 上尝试了多个建议,使用 for 循环和 numpy 的 savetxt 方法。 (我不需要使用 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,每个项目都用单引号括起来。


您可以使用以下方法实现此目的DataFrame.applymap https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.applymap.html and DataFrame.merge https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html像这样:

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'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Python Pandas Dataframe 中的字符串和整数列中的项目周围添加单引号 的相关文章

随机推荐