python - 处理一列列表时,如何使用 to_tsv() 将单引号切换为双引号?

标签 python pandas

如果我有一个数据框

df = pd.DataFrame({0: "text", 1: [["foo", "bar"]]})
df
      0           1
0  text  [foo, bar]
我将 df 写到这样的 tsv 文件中
df.to_csv('test.tsv',sep="\t",index=False,header=None, doublequote=True)
tsv 文件看起来像这样
text    ['foo', 'bar']
如何确保我的列表项周围有双引号并使 test.tsv 看起来像这样?
text    ["foo", "bar"]

最佳答案

试试 json.dumps

import json
df[1]=df[1].map(json.dumps)
然后
df.to_csv('test.tsv', sep="\t", index=False, header=None, doublequote=True, quoting=csv.QUOTE_NONE)

关于python - 处理一列列表时,如何使用 to_tsv() 将单引号切换为双引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64344943/

相关文章:

python - 仅替换匹配表达式中的特定组

python - 如何使用Python获取XML文件中child->child->child->child的内容

python - 在for循环中将数据添加到Pandas Dataframe

python - 在 Python 中使用数据框值填充预定义字符串?

python - 用lxml组合多个标签

python - 在数组中查找重复项 - 时间复杂度 < O(n^2) 和常量额外空间 O(1)。 (亚马逊采访)

python - 划分两个 pandas DataFrames 并保留非数字列

Python .loc 困惑

python - python 中缺失值的统计

python - Pandas 列中的精确匹配字符串