如何在 Python 中创建数据帧数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33907776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create an array of dataframes in Python
提问by Ana
I want to write a piece of code to create multiple arrays of dataFrames with their names in the format of word_0000, where the four digits are month and year. An example of what I'd like to do is to create the following dataframes:
我想编写一段代码来创建多个数据帧数组,其名称格式为 word_0000,其中四位数字是月份和年份。我想做的一个例子是创建以下数据帧:
df_0115, df_0215, df_0315, ... , df_1215
stat_0115, stat_0215, stat_0315, ... , stat_1215
采纳答案by Pedro M Duarte
I suggest that you create a dictionary to hold the DataFrames
. That way you will be able to index them with a month-day
key:
我建议你创建一个字典来保存DataFrames
. 这样你就可以用一个month-day
键来索引它们:
import datetime as dt
import numpy as np
import pandas as pd
dates_list = [dt.datetime(2015,11,i+1) for i in range(3)]
month_day_list = [d.strftime("%m%d") for d in dates_list]
dataframe_collection = {}
for month_day in month_day_list:
new_data = np.random.rand(3,3)
dataframe_collection[month_day] = pd.DataFrame(new_data, columns=["one", "two", "three"])
for key in dataframe_collection.keys():
print("\n" +"="*40)
print(key)
print("-"*40)
print(dataframe_collection[key])
The code above prints out the following result:
上面的代码打印出以下结果:
========================================
1102
----------------------------------------
one two three
0 0.896120 0.742575 0.394026
1 0.414110 0.511570 0.268268
2 0.132031 0.142552 0.074510
========================================
1103
----------------------------------------
one two three
0 0.558303 0.259172 0.373240
1 0.726139 0.283530 0.378284
2 0.776430 0.243089 0.283144
========================================
1101
----------------------------------------
one two three
0 0.849145 0.198028 0.067342
1 0.620820 0.115759 0.809420
2 0.997878 0.884883 0.104158
回答by mussabaheen
df
will have all the CSV files you need.
df[0]
to access first one
df
将拥有您需要的所有 CSV 文件。
df[0]
访问第一个
df=[]
files = glob.glob("*.csv")
for a in files:
df.append( pd.read_csv(a))