Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
15
Help us understand the problem. What is going on with this article?
@16kirin

Pandas to_csv関数でCSVファイルにダブルクォーテーションを2個続けて出力する方法

More than 1 year has passed since last update.

PythonでCSVファイルを出力する際に、ダブルクォーテーションを2個続けて出力するのにハマったのでメモ。

動作確認環境

OS Windows8.1
Python 3.6.4
pandas 0.22.0

対応方法

to_csv関数のquoting引数に csv.QUOTE_NONNUMERIC を指定。

サンプルコード

import pandas as pd
import csv
import numpy

# データフレームにデータをセット
df = pd.DataFrame([{'data1': 'ABC', 'data2': 100, 'data3': 3.14, 'data4': numpy.nan, 'data5': '', 'data6': ""}])

# CSVファイルを出力
df.to_csv('output.csv', index=False, encoding='utf-8', quoting=csv.QUOTE_NONNUMERIC)

CSVファイル出力結果

"data1","data2","data3","data4","data5","data6"
"ABC",100,3.14,"","",""

【参考】quoting引数によるCSVファイル出力結果の違い

quoting=csv.QUOTE_MINIMAL ←デフォルト値

<CSVファイル出力結果>
data1,data2,data3,data4,data5,data6
ABC,100,3.14,,,

quoting=csv.QUOTE_NONE

<CSVファイル出力結果>
data1,data2,data3,data4,data5,data6
ABC,100,3.14,,,

quoting=csv.QUOTE_ALL

<CSVファイル出力結果>
"data1","data2","data3","data4","data5","data6"
"ABC","100","3.14","","",""

quoting=csv.QUOTE_NONNUMERIC ←本文から再掲

<CSVファイル出力結果>
"data1","data2","data3","data4","data5","data6"
"ABC",100,3.14,"","",""

15
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
15
Help us understand the problem. What is going on with this article?