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

python:分组数据时将最早的数据保留在新列中,python,pandas,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.Data

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

以下是:

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
上分组,以便将所有A条目的第一次出现时间设置为min_date,等等。

我想您需要以下方法:

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

>>> 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]