如何將每個資料幀存盤到一個唯一的變數中(即;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)
uj5u.com熱心網友回復:
正如評論中提到的,您可以使用字典:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/339907.html
