如何使用 python 从数据框创建多个 Pandas 时间序列?
How to create multiple Pandas time series from a data frame using python?
我从一个如下所示的 Pandas 数据框开始:
Type Date Number
1 A x y
2 B x y
3 A x y
4 B x y
5 A x y
我想分别为 A 类数据和 B 类数据创建单独的时间序列。最有效的方法是什么?
我正在考虑从中创建两个不同的数据帧,其中每个数据只有一种类型的数据,然后将每个单独的数据帧转换为一个系列。但是我也不知道该怎么做。
扩展问题:如果你连有多少种不同的类型都不知道,有没有办法做到这一点?
到目前为止,我尝试使用 df["type"] == A
来检查类型是否是我想要的类型,但这并没有给我一个完整的数据框,只是一个数据框说类型是否是对或错。
附加信息:
我的目标是使用类型 A
和类型 B
的日期和数字数据创建单独的 pandas 时间序列。
我尝试了以下方法:
df.groupBy("Type").apply(lambda x: x.Date)
上述功能有效,但只有 returns 一列。
df.groupBy("Type").apply(lambda x: (x.Date, x.Number))
上面的功能不起作用,returns完全不是我想要的东西。
预期输出:
Type Date Number
A 1 x y
3 x y
5 x y
B 2 x y
4 x y
如果您想按类型对日期进行分组并将它们放入一个单独的系列中,您可以执行以下操作。
按类型分组:
grouped = df.groupby('Type')
从每个组中获取日期:
dates = grouped.apply(lambda x:x.Date)
dates
现在看起来像这样:
Type
A 1 x
3 x
5 x
B 2 x
4 x
您可以按类型名称访问系列:dates.A, dates.B
等
So far I tried checking to see if the type is of the type I want by using df["type"] == A, and this doesn't give me a full data frame back just a data frame saying if the type was true or false.
df["type"] == A
给你一个布尔掩码,你可以把它插回数据框:df[df["type"] == A]
不过这是一个很基础的pandas操作,看看官方教程,例子很多:http://pandas.pydata.org/pandas-docs/stable/tutorials.html
我从一个如下所示的 Pandas 数据框开始:
Type Date Number
1 A x y
2 B x y
3 A x y
4 B x y
5 A x y
我想分别为 A 类数据和 B 类数据创建单独的时间序列。最有效的方法是什么?
我正在考虑从中创建两个不同的数据帧,其中每个数据只有一种类型的数据,然后将每个单独的数据帧转换为一个系列。但是我也不知道该怎么做。
扩展问题:如果你连有多少种不同的类型都不知道,有没有办法做到这一点?
到目前为止,我尝试使用 df["type"] == A
来检查类型是否是我想要的类型,但这并没有给我一个完整的数据框,只是一个数据框说类型是否是对或错。
附加信息:
我的目标是使用类型 A
和类型 B
的日期和数字数据创建单独的 pandas 时间序列。
我尝试了以下方法:
df.groupBy("Type").apply(lambda x: x.Date)
上述功能有效,但只有 returns 一列。
df.groupBy("Type").apply(lambda x: (x.Date, x.Number))
上面的功能不起作用,returns完全不是我想要的东西。
预期输出:
Type Date Number
A 1 x y
3 x y
5 x y
B 2 x y
4 x y
如果您想按类型对日期进行分组并将它们放入一个单独的系列中,您可以执行以下操作。
按类型分组:
grouped = df.groupby('Type')
从每个组中获取日期:
dates = grouped.apply(lambda x:x.Date)
dates
现在看起来像这样:
Type
A 1 x
3 x
5 x
B 2 x
4 x
您可以按类型名称访问系列:dates.A, dates.B
等
So far I tried checking to see if the type is of the type I want by using df["type"] == A, and this doesn't give me a full data frame back just a data frame saying if the type was true or false.
df["type"] == A
给你一个布尔掩码,你可以把它插回数据框:df[df["type"] == A]
不过这是一个很基础的pandas操作,看看官方教程,例子很多:http://pandas.pydata.org/pandas-docs/stable/tutorials.html