python pandas:在分组数据时将最早的数据保存在新列中

时间:2014-04-15 20:18:09

标签: python pandas

我尝试按列进行分组,找到该组中的最小日期值,并将其插入该列中所有值的新列中。

以下内容:

d = {'one' : pd.Series(np.random.randn(6), index=pd.date_range('1/1/2011', periods=6, freq='H')),
     'two' : pd.Series(["A", "B", "C"] * 2, index=pd.date_range('1/1/2011', periods=6, freq='H'))}
df = pd.DataFrame(d)
df['ts'] = df.index
df['min_date'] = df.groupby('two')['ts'].min()
df

给了我这个输出:

Out[7]: 
                          one two                  ts min_date
2011-01-01 00:00:00  1.676829   A 2011-01-01 00:00:00      NaT
2011-01-01 01:00:00 -0.490976   B 2011-01-01 01:00:00      NaT
2011-01-01 02:00:00 -1.934902   C 2011-01-01 02:00:00      NaT
2011-01-01 03:00:00 -0.625931   A 2011-01-01 03:00:00      NaT
2011-01-01 04:00:00  1.534645   B 2011-01-01 04:00:00      NaT
2011-01-01 05:00:00  0.123045   C 2011-01-01 05:00:00      NaT

[6 rows x 4 columns]

我想要的地方:

Out[7]: 
                          one two                  ts                 min_date
2011-01-01 00:00:00  1.676829   A 2011-01-01 00:00:00      2011-01-01 00:00:00
2011-01-01 01:00:00 -0.490976   B 2011-01-01 01:00:00      2011-01-01 01:00:00
2011-01-01 02:00:00 -1.934902   C 2011-01-01 02:00:00      2011-01-01 02:00:00
2011-01-01 03:00:00 -0.625931   A 2011-01-01 03:00:00      2011-01-01 00:00:00
2011-01-01 04:00:00  1.534645   B 2011-01-01 04:00:00      2011-01-01 01:00:00
2011-01-01 05:00:00  0.123045   C 2011-01-01 05:00:00      2011-01-01 02:00:00

[6 rows x 4 columns]

对列two进行分组,以便在min_date中为所有A条目等设置A的第一次出现。

1 个答案:

答案 0 :(得分:2)

我想你想要transform方法:

>>> df['min_date'] = df.groupby('two')['ts'].transform("min")
>>> df
                          one two                  ts            min_date
2011-01-01 00:00:00  0.574285   A 2011-01-01 00:00:00 2011-01-01 00:00:00
2011-01-01 01:00:00 -0.200439   B 2011-01-01 01:00:00 2011-01-01 01:00:00
2011-01-01 02:00:00  0.549725   C 2011-01-01 02:00:00 2011-01-01 02:00:00
2011-01-01 03:00:00  1.187299   A 2011-01-01 03:00:00 2011-01-01 00:00:00
2011-01-01 04:00:00  0.770180   B 2011-01-01 04:00:00 2011-01-01 01:00:00
2011-01-01 05:00:00 -0.448781   C 2011-01-01 05:00:00 2011-01-01 02:00:00

[6 rows x 4 columns]

用于执行聚合操作,然后将结果广播到整个组。