class Class_test:
def __init__(self):
self.fun_5_1()
# 若无则报错AttributeError: 'Class_test' object has no attribute 'fun_zip'
def fun_zip(
self,
df_arg=pd.DataFrame(),
bool_arg=False
):
# 每列元素打包
zipped = zip(*[df_arg.iloc[i] for i in range(df_arg.shape[0])])
# 是否包含标题
if bool_arg:
list_zip = [(col_name, *row) for col_name, row in zip(df_arg.columns, zipped)]
else:
list_zip = [tuple(row) for row in zipped]
return list_zip
def fun_columns(
self,
list_columns=[str(i)+'_重量' if int(i[3])//2 else i for i in ['col'+str(j) for j in range(3)]],
str_keyword='重量',
str_suffix='合计'
):
dict_columns={
key: value for key, value in zip(
list_columns,
[
str(z) + str(str_suffix)
if str(str_keyword) in str(z)
else None
for z in list_columns
]
)
}
return dict_columns
def fun_5_1(self):
self.dict_columns = self.fun_columns()
def fun_sum(
self,
df_arg=pd.DataFrame(columns=['col0', 'col1', 'col2_重量']),
int_arg=0,
bool_on=False,
list_on=['column_to_merge_on'],
list_LookupValue=['lookup_value']
):
# 生成1行表格
# 增加合计列,填入合计重量
list_values = [value for value in self.dict_columns.values() if value is not None]
df_zip_arg = pd.DataFrame(
data={
key: str(value) for key, value in zip(df_arg.columns, self.fun_zip(df_arg))
},
index=[int_arg]
)
df_zip_arg = pd.concat(
objs=[
df_zip_arg,
pd.DataFrame(columns=list_values)
],
axis=1
)
if df_arg.shape[0] > 0:
for value in list_values:
df_zip_arg.loc[int_arg, value] = df_arg.loc[
:, [k for k, v in self.dict_columns.items() if v == value][0]
].sum()
# 如果需要新增str_on列以供匹配
if bool_on:
df_zip_arg = pd.concat(
objs=[
pd.DataFrame(columns=list_on),
df_zip_arg
],
axis=1
)
if df_arg.shape[0] > 0:
dict_on = {k: v for k, v in zip(list_on, list_LookupValue)}
for key in dict_on.keys():
df_zip_arg.loc[int_arg, key] = [v for k, v in dict_on.items() if k == key][0]
return df_zip_arg
obj_test = Class_test() # 若无括号则报错TypeError: Class_test.fun_sum() missing 1 required positional argument: 'self'
obj_test.fun_sum(pd.DataFrame([[1,1,1],[2,2,2],[3,3,3]],columns=['col0', 'col1', 'col2_重量']))
obj_test.fun_sum(pd.DataFrame(columns=['col0', 'col1', 'col2_重量']))
obj_test.fun_sum(pd.DataFrame([[1,1,1],[2,2,2],[3,3,3]],columns=['col0', 'col1', 'col2_重量']), bool_on=True)
obj_test.fun_sum(pd.DataFrame(columns=['col0', 'col1', 'col2_重量']), bool_on=True)
标签:匹配,表格,zip,df,list,以供,arg,fun,columns
From: https://blog.51cto.com/u_16055028/7151654