我必須兩次使用相同的功能。引數為 時為第一個,引數為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'
uj5u.com熱心網友回復:
add函式的名稱與變數名稱df和df3腳本的其余部分無關。
正如@garagnoth 所說,您只需要add. 您可以將其稱為df, fooor myvariablename:它與 no df、nor 無關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作為腳本的其余部分已經這樣做。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/313626.html
