“Wrap each item in my dataset with double quotes not reading to csv”

huangapple go评论83阅读模式
英文:

Wrap each item in my dataset with double quotes not reading to csv

问题

这让我感到非常困扰。

期望的输出:

id name last_name datetime lat long
"1" "Stack" "Overflow" "2024-01-01" "40.21324" "39.6969"

问题:我可以在Jupyter Notebook中将每个项目都用双引号括起来,但当我读取到CSV时,双引号就丢失了。
我有一个包含各种不同字段的数据集。
例如:

123, Peter, 40.83429, 2023-10-23

我想用双引号包裹每个字段:

 "123", "Peter", "40.83429", "2023-10-23"

我的代码:
当我在Jupyter Notebook中重新读取CSV时会发生什么:

用双引号添加代码:

all_cols = list(df) 
for i in all_cols:
    df[i] = '"' + df[i] + '"' 

用于将其读取到CSV中的代码:

df.to_csv('test1.csv')

然而,当我打开我的CSV文件时,它仍然没有用双引号括起来。我做错了什么?非常感谢您提前帮助我,这让我非常困扰。

英文:

This is driving me nuts.

Input:

id name last_name datetime lat long
1 Stack Overflow 2024-01-01 40.21324 39.6969

Desired output:

id name last_name datetime lat long
"1" "Stack" "Overflow" "2024-01-01" "40.21324" "39.6969"

Issue: I am able to wrap each item in double quotes in Jupyter Notebook but when I read to CSV I lose the double quotes.
I have a dataset with a bunch of different fields.
For example:

123, Peter, 40.83429, 2023-10-23

I want to wrap every field with a double quote:

 "123", "Peter", "40.83429", "2023-10-23"

My code:
What happens when I read back the csv in Jupyter Notebook:

Code to add double quotes:

all_cols = list(df) 
for i in all_cols:
    df[i] = '"' + df[i] + '"' 

Code to read that into the csv:

df.to_csv('test1.csv')

However, when I open my CSV file it's STILL not wrapped in double quotes. What am I doing wrong? Thank you SO MUCH in advance this is driving me absolutely nuts.

答案1

得分: 1

to_csv方法有一个相应的标志。它使用了csv模块中的QUOTE标志。

df.to_csv('test1.csv', quoting=csv.QUOTE_ALL)
英文:

The to_csv method has a flag for that. It uses the QUOTE flags from the csv module

df.to_csv('test1.csv', quoting=csv.QUOTE_ALL)

答案2

得分: 0

这将完成它:

import csv

out = open('test1.csv', 'w')
for row in csv.reader(open('test.csv')):
    print(','.join(f'"{x}"' for x in row), file=out)
英文:

This will do it:

import csv

out = open('test1.csv','w')
for row in csv.reader(open('test.csv')):
    print( ','.join(f'"{x}"' for x in row), file=out)

huangapple
  • 本文由 发表于 2023年8月4日 04:14:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76831373.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定