dynamically rename data frame in Python

守給你的承諾、 提交于 2019-12-25 18:26:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!