简体   繁体   中英

Create new column from nth value in a groupby group with Python pandas

Given a dataset with a categorical object type, a day of measurement, and the value measured, I want to add a new column to the dataset that gives the value of that type on the nth measurement day. For example, if type 'a' was measured to have value 8 on the first day measured and type 'b' was measured to have value 12 on the first day measured, I want the new column "value on first day measured" to show 8 for all rows of type 'a' and 12 for all rows of type 'b'. Can this be done with pandas DataFrames in Python (version 2)? The data set could look like:

from pandas import DataFrame
df = DataFrame([['a',2,8],['a',5,9],['b',3,12],['b',15,21]])
df.columns = ['type','day','value']

>>> df
  type  day  value
0    a    2      8
1    a    5      9
2    b    3     12
3    b   15     21

I want it to eventually look like this:

  type  day  value  value on first day measured
0    a    2      8                            8
1    a    5      9                            8
2    b    3     12                           12
3    b   15     21                           12

I can get the measurement values on the first day measured like this:

g = df.groupby('type')
g.nth(0)['value']

The output is:

>>> g.nth(0)['value']
type
a     8
b    12

but I can't figure out how to put those values back into df as a new column.

这是一个班轮:

df.groupby('type').apply(lambda x : x.assign(val1st = x.sort_values(by='day')['value'].head(1).values[0])).reset_index(drop=True)

use groupby followed by transform :

>>> i = df.groupby('type')['day'].transform('idxmin')
>>> df['val@1st'] = df.loc[i, 'value'].values
>>> df
  type  day  value  val@1st
0    a    2      8        8
1    a    5      9        8
2    b   11     12       12
3    b   15     21       12

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM