问题
I'm trying to dynamically create datasets:
def CreateDF (indsn, outdsn):
outdsn = pd.DataFrame(indsn)
....
return outdsn
CreateDF (phase_df, phase_df2)
But it does not work, I get the following error:
NameError: name 'phase_df2' is not defined
Being able to do the above could be useful because I could also loop through a list of datasets (for each datasets in the list), but I'm not sure how to dynamically rename them.
回答1:
It's a little sparse because you didn't give us info on why this needs to happen, or what your source material looks like, but the general idea is:
def make_df(name):
...
return df
dict_of_dfs = dict()
df_names = [] #a list of all the dataframes you want to create
for name in df_names:
dict_of_dfs[name] = make_df(name)
Now instead of variables, you can name dictionary entries as keys and each value will be the dataframe.
回答2:
Initialise df:
df= pd.DataFrame(index=range(0,4),columns=['A','B','C','D'], dtype='object')
dynamically add:
for values in values_np
df.set_value([iterator, 'A', values)
iterator += 1
This way you can dynamically add row wise
来源:https://stackoverflow.com/questions/38058008/dynamically-rename-data-frame-in-python