欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数据分析-pandas存储文本文件

程序员文章站 2024-01-19 14:50:28
...
import pandas as pd

df = pd.read_csv('datafile/data4.csv')

print(df)
    k1 k2   k3    k4
0  one  a  1.0  11.0
1  one  b  2.0   NaN
2  one  c  3.0  13.0
3  one  d  NaN  14.0
4  one  e  5.0  15.0
5  two  f  6.0   NaN
6  two  g  7.0  17.0
7  two  h  NaN  18.0
8  two  i  9.0  19.0
df = pd.read_csv('datafile/data4.csv')

df.to_csv('datafile/outer4.csv')
# 生成 csv 文件

pd.read_csv('datafile/outer4.csv')
Unnamed: 0 k1 k2 k3 k4
0 0 one a 1.0 11.0
1 1 one b 2.0 NaN
2 2 one c 3.0 13.0
3 3 one d NaN 14.0
4 4 one e 5.0 15.0
5 5 two f 6.0 NaN
6 6 two g 7.0 17.0
7 7 two h NaN 18.0
8 8 two i 9.0 19.0
df = pd.read_csv('datafile/data4.csv')

df.to_csv('datafile/outer5.csv', na_rep="0")
# na_rep 设置缺失值存储在文件中的值

pd.read_csv('datafile/outer5.csv')
Unnamed: 0 k1 k2 k3 k4
0 0 one a 1.0 11.0
1 1 one b 2.0 0.0
2 2 one c 3.0 13.0
3 3 one d 0.0 14.0
4 4 one e 5.0 15.0
5 5 two f 6.0 0.0
6 6 two g 7.0 17.0
7 7 two h 0.0 18.0
8 8 two i 9.0 19.0
df = pd.read_csv('datafile/data4.csv')

df.to_csv('datafile/outer6.csv',index=False, header=False)
# 不写出列名和行名

pd.read_csv('datafile/outer6.csv')
one a 1.0 11.0
0 one b 2.0 NaN
1 one c 3.0 13.0
2 one d NaN 14.0
3 one e 5.0 15.0
4 two f 6.0 NaN
5 two g 7.0 17.0
6 two h NaN 18.0
7 two i 9.0 19.0
df = pd.read_csv('datafile/data4.csv')

df.to_csv('datafile/outer7.csv',index=False, header=False, columns=['k1', 'k2', 'k3', 'k4'])
# columns 指定写入的列

pd.read_csv('datafile/outer7.csv')
one a 1.0 11.0
0 one b 2.0 NaN
1 one c 3.0 13.0
2 one d NaN 14.0
3 one e 5.0 15.0
4 two f 6.0 NaN
5 two g 7.0 17.0
6 two h NaN 18.0
7 two i 9.0 19.0
df = pd.read_csv('datafile/data4.csv')
print(df)
df.to_csv('datafile/outer8.csv', na_rep='0',index=False,header=['A', 'B', 'C', 'D'])
# header 设置列名
# index_label 不会用啊!!!

pd.read_csv('datafile/outer8.csv')
    k1 k2   k3    k4
0  one  a  1.0  11.0
1  one  b  2.0   NaN
2  one  c  3.0  13.0
3  one  d  NaN  14.0
4  one  e  5.0  15.0
5  two  f  6.0   NaN
6  two  g  7.0  17.0
7  two  h  NaN  18.0
8  two  i  9.0  19.0
A B C D
0 one a 1.0 11.0
1 one b 2.0 0.0
2 one c 3.0 13.0
3 one d 0.0 14.0
4 one e 5.0 15.0
5 two f 6.0 0.0
6 two g 7.0 17.0
7 two h 0.0 18.0
8 two i 9.0 19.0
相关标签: 数据分析