python - 在 Pandas 中动态命名 DataFrame

标签 python python-2.7 pandas

假设我有 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']

有什么帮助吗?

最佳答案

我想不出有什么理由不能使用 DataFrame 的字典。这将使您避免将变量名视为数据:

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]})

关于python - 在 Pandas 中动态命名 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32577939/

相关文章:

Python 使用空格分隔从 csv 读取数据(第一列除外)

Python Twitter JSON 无法提取位置、地点或时区

python - 从python中的max函数获取有线结果

c++ - 使用 CUDA 实现、python (pycuda) 或 C++ 处理图像?

python - 将每 3 行连接在一起 Python

python - 根据多个其他列的值选择和更改第三个值

python - 使用 list(filter()) 的程序在 python 3 上运行速度极慢

python - Conda 创建卡在 "solving package specifications"

Python Pandas Dataframe 追加行

Python数据帧: fill text in certain rows if other columns satisfied