【问题标题】:Dynamically naming DataFrames in Pandas在 Pandas 中动态命名 DataFrame
【发布时间】:2015-09-15 04:49:45
【问题描述】:

假设我有 2 个这样的数据框:

foo = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]})
bar = pd.DataFrame({'c':[7,8,9], 'd':[10,11,12]})

我想对这些数据帧中的每一个进行子集化,并将它们放入具有动态名称的新数据帧中。当我在 python 中查找有关动态命名的任何内容时,他们说,不要这样做,使用dictionary。 我无法完全弄清楚如何使它工作。基本上我想要以下内容:

foo_first = foo[0:1]
bar_first = bar[0:1]

但我希望能够在列表中循环。如果我想用字典来做,我会想象它是这样的:

dfs_list = [foo, bar]
dfs_dict = {}

for x in dfs_list:
    dfs_dict[x+'_first']=foo[0:1]

这不起作用。

您可能想知道我实际上想要做什么,因为我的示例是如此武断且毫无意义。在我的真实示例中,我有几个按日期索引的数据框。我想根据当前年份和月份的这些旧数据框的名称创建新的数据框。所以如果 foo 和 bar 是带有日期索引的巨型数据集,我想自动化:

foo_year = foo['2015-01-01':'2015-12-31']
bar_year = bar['2015-01-01':'2015-12-31']
foo_month = foo['2015-08-01':'2015-08-31']
bar_month = foo['2015-08-01':'2015-08-31']

有什么帮助吗?

【问题讨论】:

    标签: python python-2.7 pandas


    【解决方案1】:

    我想不出你不能使用DataFrames 的字典的任何原因。这将使您避免将变量名称视为数据:

    whole_dataframes = {"foo": foo, "bar": bar}
    first_dataframes = {name: value[:1] for name, value in whole_dataframes.items()}
    

    我正在使用您描述的foobar 变量来初始化第一个字典,但您可以跳过该步骤,直接在字典中创建值:

    whole_dataframes = {}
    whole_dataframes["foo"] = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]})
    whole_dataframes["bar"] = pd.DataFrame({'c':[7,8,9], 'd':[10,11,12]})
    

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 2013-11-19
      • 2019-07-21
      • 2017-05-30
      • 2013-12-18
      • 1970-01-01
      • 2017-03-05
      相关资源
      最近更新 更多