我必须使用相同的函数两次。参数为df
时为第一次,参数为df3
时为第二次。怎么做呢?功能:
def add(df, df3):
df["timestamp"] = pd.to_datetime(df["timestamp"])
df = df.groupby(pd.Grouper(key = "timestamp", freq = "h")).agg("mean")
price = df["price"]
amount = df["amount"]
return (price * amount) // amount
双重用途:
out = []
# This loop will use the add(df) function for every csv and append in a list
for f in csv_files:
df = pd.read_csv(f, header=0)
# Replace empty values with numpy, not sure if usefull, maybe pandas can handle this
df.replace("", np.nan)
#added aggregate DataFrame with new column to list of DataFrames
out.append(add(df))
out2 = []
df3 = pd.Series(dtype=np.float64)
for f in csv_files:
df2 = pd.read_csv(f, header=0)
df3 = pd.concat([df3, df2], ignore_index=True)
out2 = pd.DataFrame(add(df = df3))
out2
我得到了错误:
TypeError: add() missing 1 required positional argument: 'df3'
add
函数的名称与脚本其余部分的df
和df3
变量名称无关。
正如@garagnoth所说,在add
中只需要一个参数。你可以叫它df
、foo
或myvariablename
,它与df
和df3
都没有关系。
在您的情况下,您可以将add
函数更改为以下内容:
def add(a_dataframe):
# I set the argument name to "a_dataframe" so you can
# see its name is not linked to outside variables
a_dataframe["timestamp"] = pd.to_datetime(a_dataframe["timestamp"])
a_dataframe = a_dataframe.groupby(pd.Grouper(key = "timestamp", freq = "h")).agg("mean")
price = a_dataframe["price"]
amount = a_dataframe["amount"]
return (price * amount) // amount
您现在可以使用df
或df3
调用此函数,就像脚本的其余部分一样。