我需要在 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
Run Code Online (Sandbox Code Playgroud)
最后,想看到 4 列:id、person、id_with_quotes、person_with_quotes。列 id 和 person 保持不变。id_with_quotes、person_with_quotes 列是 id 和 person,每个项目都用单引号括起来。
如果我正确地阅读了你的问题,你可以做这样的事情。基本上遍历每一列,并在列中每个项目的开头和结尾添加引号。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()
Run Code Online (Sandbox Code Playgroud)
这给出了这个输出
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'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18185 次 |
| 最近记录: |