這是一個奇怪的問題,但我創建了一個函式,它利用pivot_table和一些過濾和重命名來應用于我需要的一堆資料透視/聚合用例。
該函式的引數之一是聚合函式串列,即np.median. 該函式的另一個引數是參考該聚合函式的字串,即median.
我只有后一個引數,所以我可以用它來過濾列。我想知道是否有辦法從創建子字串np.median?理想情況下,除了 numpy 函式之外,我不需要字串引數。
我發現的挑戰是np.median(或任何 numpy 聚合函式)有一個型別[<function median at 0x7fa1d043b700>],所以我不能用任何字串拆分操作來處理它以從中提取median。
這可能嗎?
示例資料框
data = [
["2", "dog", "groomed", 100],
["2", "dog", "groomed", 90],
["2", "dog", "ungroomed", 30],
["3", "cat", "groomed", 25],
["3", "cat", "ungroomed", 10],
]
df = pd.DataFrame(data, columns=["ID", "pet", "status", "amount"])
功能
from typing import List
def long_to_wide_reshape_w_agg(
input_df: pd.DataFrame,
index_list: List[str],
col_to_pivot: str,
vals: str,
suffix: str,
aggs: List = np.mean,
agg_method: str = "mean",
):
# identify possible values for the column we want to pivot on
# we need these to filter out columns we want to rename in later steps
cols = input_df[col_to_pivot].unique().tolist()
str_cols = [x for x in cols if isinstance(x, str)]
reshaped_df = input_df.pivot_table(
index=index_list,
columns=col_to_pivot,
aggfunc=aggs,
values=vals,
).reset_index()
# flatten hierarchical index
reshaped_df.columns = [" ".join(col).strip() for col in reshaped_df.columns.values]
# identify columns to rename
cols_to_rename = [
s for s in reshaped_df.columns.values if any(subs in s for subs in str_cols)
]
tuple_cols = tuple(cols_to_rename)
# rename columns as needed
reshaped_df = reshaped_df.rename(
columns=lambda col: f"{col}{suffix}" if col in tuple_cols else col
)
# remove spaces and replace with underscores
reshaped_df.columns = [cols.replace(" ", "_") for cols in reshaped_df.columns]
# based on agg_method chosen, filter to ensure there are no null values for those columns
col1, col2 = [col for col in reshaped_df.columns if agg_method in col]
print(col1)
print(col2)
### do stuff with col1/col2
return reshaped_df
功能用例
long_to_wide_reshape(
input_df=df,
index_list=["ID", "pet"],
col_to_pivot="status",
aggs=[np.median],
vals="amount",
suffix="_amount",
agg_method="median",
)
uj5u.com熱心網友回復:
怎么用.__name__?
...
col1, col2 = [col for col in reshaped_df.columns if aggs[0].__name__ in col]
...
因為...
>>> np.median
<function numpy.median(a, axis=None, out=None, overwrite_input=False, keepdims=False)>
>>> np.median.__name__
'median'
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/430703.html
