亲爱的,
我有一个功能,根据dataframe
的某些规格列进行同步
功能正常,但我想知道如何:
请随时留下任何建议,
感谢。
输入:
df
:带有列的dataframe
:
[a0,...aN]
:a0
至aN
个名称可以是任意有效string
且包含numeric
值[agent,date]
:是固定名称,agent
包含numeric
值,date
包含datetime
。sync_with
:要与string
中包含的listof string
或[a0,..., aN]
同步的列,或默认情况下为{{ 1}}同步所有empty list
。同步:
[a0,...,aN]
。 返回:已同步的fillna
这是我的功能:
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]))