Pandas数据帧自定义前向fillna优化

时间:2018-03-01 09:49:14

标签: python python-3.x performance pandas

问题

亲爱的,
我有一个功能,根据dataframe的某些规格列进行同步 功能正常,但我想知道如何

  • 改善表现
  • 让它更加pythonic

请随时留下任何建议,
感谢。

功能,样本和结果

功能规格

  1. 输入

    • df :带有列的dataframe
      • [a0,...aN]a0aN个名称可以是任意有效string且包含numeric
      • [agent,date]:是固定名称,agent包含numeric值,date包含datetime
    • sync_with :要与string中包含的listof string[a0,..., aN]同步的列,或默认情况下为{{ 1}}同步所有empty list
  2. 同步

    • 按代理值分组前进[a0,...,aN]
    • 删除要与值同步的所有列为空的行
  3. 返回:已同步的fillna

  4. 这是我的功能:

    dataframe

    示例

    import pandas as pd
    import numpy as np
    
    def synchronize(df,sync_with=[]):
        _df = df.copy()
    
        if not isinstance(sync_with,list):
            sync_with = [sync_with]
    
        _fixed_cols = ['date','agent']
        _fixed_cols.extend(sync_with)
        _colset = [c for c in _df.columns if c not in _fixed_cols]
    
        for ag in _df.agent.unique():
            _df.loc[_df.agent==ag,_colset] = _df.loc[_df.agent==ag,_colset].fillna(method='ffill')
            if sync_with:
                _df = _df.dropna(how='all', subset=sync_with)
                _df.loc[_df.agent==ag,:] = _df.loc[_df.agent==ag,:].fillna(method='ffill')
    
        return _df
    

    结果

    foo = pd.DataFrame(dict(date=pd.to_datetime(['2010', '2011', '2012', '2013', '2010', '2013', '2015', '2016']),
                            agent=[1,1,1,1,2,2,2,2],
                            _a=[1, np.nan, np.nan, 4, 5, np.nan, 7, 8],
                            _b=[11, 22, np.nan, np.nan, 55, np.nan, 77, np.nan],
                            _c=[111, np.nan, 333, np.nan, np.nan, 666, 777, np.nan]))
    

0 个答案:

没有答案