Python pandas groupby 方法不正常工作

-1 投票
2 回答
6653 浏览
提问于 2025-04-17 23:00

我有一个文本文件,每一行都有数据,并且每一行都有一个时间戳。

所以我像这样把数据读入一个数据框:

table = pd.read_table(file, sep='|', skiprows=[1], usecols = columns, parse_dates = dateColumns, date_parser = parsedate, converters=columnsFormat)

到目前为止,一切都很好。

我的结果是一个数据框,像下面这个例子:

Name Local  Code Date        Value
A1   Here   01   01-01-1990  1.2
A1   Here   01   01-02-1990  0.8
A1   Here   01   01-03-1990  1.6
...
A2   There  02   01-01-1990  1.1
A2   There  02   01-02-1990  0.7
A2   There  02   01-03-1990  1.3
...
An   Where  n    12-31-2013  2.1

日期是按时间顺序排列的,不过我有几个组,它们的元素数量不一样。

我想做的是根据 NameLocalCode 来对数据框进行分组。这样我就可以把这些值作为索引,把日期和数值作为组的列。

就像下面这个例子:

(Index)            Date        Value
(A1   Here   01)   01-01-1990  1.2
                   01-02-1990  0.8
                   01-03-1990  1.6
...
(A2   There  02)   01-01-1990  1.1
                   01-02-1990  0.7
                   01-03-1990  1.3
...
(An   Where  n)    12-31-2013  2.1

但是当我执行

table = table.groupby(['Name', 'Local', 'Code'])

时,我得到的组是这样的。第一组包含了第一天的所有数据,第二组包含了第二天的所有数据,以此类推。

Name Local  Code Date        Value
A1   Here   01   01-01-1990  1.2
A2   There  02   01-01-1990  1.1
...
A1   Here   01   01-02-1990  0.8
A2   There  02   01-02-1990  0.7
...
A1   Here   01   01-03-1990  1.6
A2   There  02   01-03-1990  1.3
...
An   Where  n    12-31-2013  2.1

有没有什么办法可以让我按照我解释的方式进行分组?

如果我使用 table = table.groupby(['Name', 'Local', 'Code', 'Date']),我会得到一个像这样的组:

Name Local  Code Date        Value
A1   Here   01   01-01-1990  1.2
                 01-02-1990  0.8
                 01-03-1990  1.6
...
A2   There  02   01-01-1990  1.1
                 01-02-1990  0.7
                 01-03-1990  1.3
...
An   Where  n    12-31-2013  2.1

这几乎是我想要的,不过我还得根据 NameLocalCode 把它分成几个组。这样做可以吗?

在读取表格时,使用 parse_datesconverters 会对索引产生影响吗?

希望我现在说得清楚了。谢谢。

2 个回答

0

针对你最后一个问题的回答:

如果你遍历

groups = df.groupby(['name','local','code'])

你应该能得到每个组的单独数据框,也就是说:

for g, grp in groups:
    print grp
1

作为一种解决方法,你可以先设置索引,然后根据这个索引进行分组:

In [11]: df1 = df.set_index(['Name', 'Local', 'Code'])

In [12]: g = df1.groupby(df1.index)

In [13]: for i in df1.groupby(df1.index): print i
(('A1', 'Here', 1),
                       Date  Value
Name Local Code                   
A1   Here  1     01-01-1990    1.2
           1     01-02-1990    0.8
           1     01-03-1990    1.6)

撰写回答