根据单个列的不同值从单个DataFrame创建多个DataFrame

时间:2019-10-16 21:50:27

标签: python pandas dataframe

我有3天的时间序列数据,其中有多列。我只有一个DataFrame,其中包含所有3天的数据。我想要基于列名称“ Dates”的3个不同的DataFrame,即df [“ Dates”]

例如:

可用数据框为:df

enter image description here

预期产量:基于三个不同的日期

第一个数据帧:df_23

enter image description here

第二个数据帧:df_24

enter image description here

第三数据框:df_25

enter image description here

我想将所有这三个DataFrame分别用于分析。

我尝试使用下面的代码,但无法使用这三个数据框(相反,我不知道如何使用。)有人可以帮助我更好地工作我的代码吗?谢谢。

enter image description here

上面的代码只是在三个DataFrame中打印DataFrame,而这三个代码却并没有按照代码的预期!

enter image description here

1 个答案:

答案 0 :(得分:1)

不确定是将变量保存到csv中还是将其保存在内存中以备将来使用,

您可以将每个唯一值传递到字典中,并通过其值进行访问:

    print(df)
     Cal  Dates
0    85     23
1    75     23
2    74     23
3    97     23
4    54     24
5    10     24
6    77     24
7    95     24
8    58     25
9    53     25
10   44     25
11   94     25



d = {}

for frame, data in df.groupby('Dates'):
    d[f'df{frame}'] = data


print(d['df23'])
    Cal  Dates
0   85     23
1   75     23
2   74     23
3   97     23

修改更新的请求:

for k,v in d.items():
    i = (v['Cal'].loc[v['Cal'] > 70].count())
    print(f"{v['Dates'].unique()[0]} --> {i} times")
23 --> 4 times
24 --> 2 times
25 --> 1 times