pandas 输出至excel,csv,pkl

pandas 输出至文件可以选择输出至 excel、csv和pkl文件。

1. 输出至excel文件需要先安装 xlwt包

pip install xlwt

code

import pandas as pd
import numpy as np


data=pd.DataFrame({
    "group": ['A', 'B', 'C'],
    "age": [15, 25, 35],
    "test": [np.nan, np.inf, np.nan]
})

data.to_excel(
    excel_writer=r'file.xlsx', 
    sheet_name='sheet_name',
    index=False,
    columns=['age', 'test'],
    encoding='GBK',
    na_rep=0,
    inf_rep='max')

参数解析:

excel_writer:输出的文件位置

sheet_name:excel文件的表名

index:是否将索引输出

colums:要输出的列名

 encoding:编码格式,windows使用 gbk,linux、mac和Android使用 utf-8

na_rep:将空值替换为的值

inf_rep:将无穷大替换为的值

输出的文件内容:

pandas 输出至excel,csv,pkl_第1张图片

2. 保存至csv文件

import pandas as pd
import numpy as np


data=pd.DataFrame({
    "group": ['A', 'B', 'C'],
    "age": [15, 25, 35],
    "test": [np.nan, np.inf, np.nan]
})

data.to_csv(
    path_or_buf='file.csv',
    index=False,
    columns=['age', 'test'],
    encoding='gbk',
    na_rep=0,
    )

相比to_excel to_csv 没有sheet_name这个参数,文件路径名称为 path_or_buf,其他和to_excel 相同

3.保存至pkl文件

data.to_pickle(path='file.pkl')

pkl文件一般是pandas内部存取使用。效率比较高。定义path 文件保存路径即可。

pkl侧重于性能,excel侧重于阅读。

PS:

agg() 优先使用内部函数。效率比较高。

你可能感兴趣的:(Python,python,数据分析)