python pandas dataframe csv txt转excel 分组取前n行 分组随机抽样的实现

使用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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值