gpt4 book ai didi

python - 创建具有相似拼写的 pandas 数据框变量名称列表

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:22 24 4
gpt4 key购买 nike

在我的环境中,我有几个名称相似的 pandas 数据框的列表。

例如:

  import pandas as pd
import numpy as np
df_abc = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')
df_xyz = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')
df_2017 = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')
... potentially others

我想创建一个列表,自动计算我的环境中的数据帧并将它们动态地拉入列表中。

 list_of_dfs = ['df_abc','df_xyz','df_2017', 'df_anything else']  
# except done dynamically. In this example anything beginning with 'df_'
# list_of_dfs = function_help(begins with 'df_')

最佳答案

globals() 应返回全局变量的variable_name:variable_value 字典。

如果您想要名称以“df_”开头的已定义变量列表,您可以这样做:

list_of_dfs = [variable for variable in globals().keys()
if variable.startswith('df_')]

我认为必须有一种比全局存储数据帧并依赖 globals() 来获取其变量名称更好的方法。也许将它们全部存储在字典中?:

dataframes = {}
dataframes['df_1'] = pd.DataFrame()
dataframes['df_2'] = pd.DataFrame()

list_of_dfs = dataframes.keys()

关于python - 创建具有相似拼写的 pandas 数据框变量名称列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44620648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com