【问题标题】:Create DataFrame Variables Inside For Loop / Group DataFrames在 For 循环/组 DataFrames 中创建 DataFrame 变量
【发布时间】:2021-10-24 06:07:48
【问题描述】:

如何将每个数据帧存储到一个唯一的变量中(即 df1、df2、df3、...)? 是否可以在 for 循环中创建新变量?因此,它仅在需要时才创建变量。

例如,如果创建了 5 个数据帧,每个数据帧将分别存储在 df1、df2、df3、df4 和 df5 中。不会创建额外的变量。

import numpy as np
import pandas as pd

# Selects random number from 3 to 10
three_to_ten = np.random.randint(3,10)

# Random number of loops from 3 to 10
for x in range(0,three_to_ten):

  # Creates random number of dataframe with random length
  data = np.random.randint(three_to_ten, size= three_to_ten)
  df = pd.DataFrame(data, columns=['numbers'])

  print (df)

【问题讨论】:

  • 将它们放在列表或字典中,忘记唯一变量。这是 python,不是 BASIC
  • @hpaulj 创建字典的好主意

标签: python pandas numpy variables


【解决方案1】:

如 cmets 中所述,您可以使用 dict:

import numpy as np
import pandas as pd

three_to_ten = np.random.randint(3, 10)
dataframes = {}

for x in range(0, three_to_ten):
  data = np.random.randint(three_to_ten, size=three_to_ten)
  df = pd.DataFrame(data, columns=['numbers'])
  dataframes[f'df{x}'] = df

print(dataframes)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    • 2020-11-02
    • 2019-06-14
    • 2014-11-24
    相关资源
    最近更新 更多