【问题标题】:Dynamically capture the values in loop while creating a pandas dataframe在创建熊猫数据框时动态捕获循环中的值
【发布时间】:2020-07-15 23:21:49
【问题描述】:

在创建数据框时,我希望在变量中捕获年份和月份值。例如,对于第一次传递,数据帧名称应为 df_2019_1 等等。任何建议将不胜感激!!!

year = [2019]
month = [1,2,3]

for year in year:
  for month in month:
      df_year_month = pd.DataFrame()

【问题讨论】:

  • 与当地人一起尝试?
  • @YOBEN_S:对不起,我是 Python 新手,本地人是什么意思?
  • 真的不推荐直接访问当地人,即使是答案的发布者 - 我知道是你:)

标签: python pandas


【解决方案1】:

你不能在 python 中访问这样的名字,但你可以将它们存储在字典中,year in year 也是覆盖的。

years = [2019]
months = [1,2,3]

df_dict = {}

for year in years:
  for month in months:
    df_dict[(year, month)] = pd.DataFrame()

print(df_dict[(2019, 1)])

附言这是用您的语法编写的,但请在此处考虑 List/Dict 理解

【讨论】:

    猜你喜欢
    • 2015-09-12
    • 2017-02-13
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 2020-04-02
    相关资源
    最近更新 更多