使用python pandas的dataframe进行大量数据的分组取前n个和分组随机抽样简直不要太高效,锤爆excel。
示例代码如下:
import pandas as pd
'''
author:LancerWu
email:wuxs231@163.com
'''
# txt转excel的函数
def txt_to_xlxs(file_name, xlsx_name, sheetname='sheet1', header=0, cols=None, sep_type='\t',
duplicate=False, subset=None, subset_type='first',
groupby=False, group_key=None, group_sort_key=None,
group_head=False, keep_head=10,
group_frac=False, keep_frac=0.1):
'''
:param file_name: 要读取的文件路径
:param xlsx_name: 要保存的文件路径
:param sheetname: 保存成excel的sheet名,默认为sheet1
:param header: 打开的csv或者txt文件是否包含列名,默认为包含,不包含设置header=None
:param cols: 如果文件不包含列名,手动传入列名
:param sep_type: 文本数据的分割方式,默认为\t
:param duplicate: 是否去重
:param subset: 用于去重的字段,多个则为list形式
:param subset_type: 去重方式,默认为保留第一个重复项
:param groupby: 是否分组
:param group_key: 用于分组的字段,多个则为list,默认为空
:param group_sort_key: 分组后排序的字段,多个则为list,默认为空
:param group_head: 是否分组并取每组的前n行
:param keep_head: 取前多少行,默认为每组的前10行
:param group_frac: 是否按比例每组取值
:param keep_frac: 每组按多少比例取行,默认为10%
:return:
'''
def chouyang(group):
'''
抽样函数
:param group:
:return:
'''
return group.sample(frac=keep_frac)
# 读取文件
df = pd.read_csv(file_name, sep=sep_type, header=header, names=cols, low_memory=False)
print(df.head())
# 去重
if duplicate:
df = df.drop_duplicates(subset=subset, keep=subset_type)
# 分组排序
if groupby:
df = df.groupby(group_key, group_keys=False).apply(lambda x: x.sort_values(group_sort_key, ascending=False))
# 排序取前n个
if group_head:
df = df.sort_values(group_sort_key, ascending=False).groupby(group_key, group_keys=False).head(keep_head)
# 分组并每组取一定比例
if group_frac:
df = df.groupby(group_key, group_keys=False).apply(chouyang)
print(df.head())
# 保存为excel
writer = pd.ExcelWriter(xlsx_name, options={'strings_to_urls': False})
df.to_excel(writer, sheetname, index=False)
writer.save()
# 单文件
filename = 'xxx.csv'
file_name = "路径"+filename+'.txt'
xlsx_name = "路径"+filename+'.xlsx'
# 列名,如果txt或者csv文件中不存在的话
cols_name = ['字段1', '字段2', ……]
# 不含列名的文本数据转为excel
txt_to_xlxs(file_name=file_name, xlsx_name=xlsx_name, header=None, cols=cols_name)
# 去重
txt_to_xlxs(file_name=file_name, xlsx_name=xlsx_name, duplicate=True, subset='字段')
# 分组排序
txt_to_xlxs(file_name=file_name, xlsx_name=xlsx_name, groupby=True, group_key='字段', group_sort_key='字段')
# 分组每组取前3行
txt_to_xlxs(file_name=file_name, xlsx_name=xlsx_name, groupby=True, group_key='字段', group_sort_key='字段',
group_head=True, keep_head=3)
# 按照每组5%的比率抽样
txt_to_xlxs(file_name=file_name, xlsx_name=xlsx_name, groupby=True, group_key='字段', group_sort_key='字段',
group_frac=True, keep_frac=0.05)