python-3.x - 在 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,每个项目都用单引号括起来。
解决方案
您可以使用以下方法实现此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'
推荐阅读
- excel - 需要动态VBA公式
- react-native - 如何在 appstoreconnect 中“准备出售”时重新上传 ipa
- kedro - 如何将数据框列表写入多张 ExcelLocalDataSet?
- javascript - 如何在 React 中调用渲染之前重置状态?
- amazon-web-services - 如何创建开发和生产 Cloudfront 密钥对?
- android - 如何访问 Helper 匿名类上的 View 对象
- javascript - 如何在浏览器中使用 JS 访问 Azure Blob 存储
- flutter - 有没有更好的方法来比较一个日期和另一个日期?
- android - 是否可以在我的应用程序中启动另一个应用程序并使用 Xamarin 点击另一个应用程序的特定坐标
- web-scraping - rvest 忽略 url 不存在并继续抓取