在For循环/组DataFrame中创建DataFrame变量



如何将每个数据帧存储为唯一变量(即;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)

正如评论中提到的,您可以使用字典:

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)

相关内容

  • 没有找到相关文章

最新更新