【python】pandas库pd.to_csv操作写入数据与自带csv库写入csv数据

通过pandas库进行数据操作时非常的简介易用,接下来简单实例来写入csv文件:

In [1]: import pandas as pd

In [2]: data = {'row1':[1,2,3,'biubiu'],'row2':[3,1,3,'kaka']}

In [3]: data
Out[3]: {'row1': [1, 2, 3, 'biubiu'], 'row2': [3, 1, 3, 'kaka']}

In [4]: data_df = pd.DataFrame(data)

In [5]: data_df
Out[5]:
     row1  row2
0       1     3
1       2     1
2       3     3
3  biubiu  kaka

In [6]: data_df.to_csv('data_df.csv')

In [7]: pd.read_csv('data_df.csv')
Out[7]:
   Unnamed: 0    row1  row2
0           0       1     3
1           1       2     1
2           2       3     3
3           3  biubiu  kaka

#index表示设定是否需要行索引,设定为FALSE表明不需要,就不会生成新的行索引
#header表明是否需要列索引,设定为True(默认设置)表明需要,那么之前df的列标签就会保存。
In [10]: data_df.to_csv('data_df.csv',index=False,header=True)

In [11]: pd.read_csv('data_df.csv')
Out[11]:
     row1  row2
0       1     3
1       2     1
2       3     3
3  biubiu  kaka

In [12]: pd.read_csv('data_df.csv').index
Out[12]: RangeIndex(start=0, stop=4, step=1)

In [13]: pd.read_csv('data_df.csv').index.values
Out[13]: array([0, 1, 2, 3], dtype=int64)

用csv包,一行一行写入

In [14]: import csv
    ...: with open("test.csv","w") as csvfile:
    ...:     writer = csv.writer(csvfile)
    ...:
    ...:     #先写入columns_name
    ...:     writer.writerow(["index","a_name","b_name"])
    ...:     #写入多行用writerows
    ...:     writer.writerows([[0,1,3],[1,2,3],[2,3,4]])
    ...:

In [15]: pd.read_csv('test.csv')
Out[15]:
   index  a_name  b_name
0      0       1       3
1      1       2       3
2      2       3       4

你可能感兴趣的:(python)