LoginSignup
0
2

More than 5 years have passed since last update.

pandas で csv の読み書き

Posted at

csv の作成

csv_create.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   csv_create.py
#
#                   Oct/01/2018
# ------------------------------------------------------------------
import sys
import pandas as pd
#
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
df = pd.DataFrame([
        ["t1271","千葉",59476,"2003-9-21"],
        ["t1272","勝浦",49573,"2003-3-14"],
        ["t1273","市原",29471,"2003-6-25"],
        ["t1274","流山",39872,"2003-8-28"],
        ["t1275","八千代",27176,"2003-10-5"],
        ["t1276","我孫子",13175,"2003-1-15"],
        ["t1277","鴨川",85134,"2003-12-21"]])

print(df)
#
path="./cities.csv"
#
df.to_csv(path,header=None,index=None)
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

次の csv が作成されます。

cities.csv
t1271,千葉,59476,2003-9-21
t1272,勝浦,49573,2003-3-14
t1273,市原,29471,2003-6-25
t1274,流山,39872,2003-8-28
t1275,八千代,27176,2003-10-5
t1276,我孫子,13175,2003-1-15
t1277,鴨川,85134,2003-12-21

csv の読み込み

csv_read.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   csv_read.py
#
#                   Oct/01/2018
# ------------------------------------------------------------------
import sys
import pandas as pd
#
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
file_csv = "./cities.csv"
#
df=pd.read_csv(file_csv,header=None)
print(df)
print(df.head())
#
df.to_csv("tmp001.csv",header=None,index=None)
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行結果

$ ./csv_read.py 
*** 開始 ***
       0    1      2          3
0  t1271   千葉  59478  2003-9-21
1  t1272   勝浦  49573  2003-3-14
2  t1273   市原  29179  2003-6-25
3  t1274   流山  39872  2003-8-28
4  t1275  八千代  29176  2003-10-5
5  t1276  我孫子  29176  2003-10-5
6  t1277   鴨川  29176  2003-10-5
       0    1      2          3
0  t1271   千葉  59478  2003-9-21
1  t1272   勝浦  49573  2003-3-14
2  t1273   市原  29179  2003-6-25
3  t1274   流山  39872  2003-8-28
4  t1275  八千代  29176  2003-10-5
*** 終了 ***
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2