pandas 在 Python 中动态重命名数据框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38058008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
dynamically rename data frame in Python
提问by tezzaaa
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
NameError: 名称 'phase_df2' 未定义
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.
能够执行上述操作可能很有用,因为我还可以遍历数据集列表(对于列表中的每个数据集),但我不确定如何动态重命名它们。
回答by Jeff
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.
现在,您可以将字典条目命名为键而不是变量,并且每个值都将是数据框。
回答by SerialDev
Initialise df:
初始化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
这样您就可以动态添加行明智