python - Find first value of column and assign to separate coulmn pandas -
assume have following dataset
table = [[datetime.datetime(2015, 1, 1), 1, 0.5], [datetime.datetime(2015, 1, 27), 1, 0.5], [datetime.datetime(2015, 1, 31), 1, 0.5], [datetime.datetime(2015, 2, 1), 1, 2], [datetime.datetime(2015, 2, 3), 1, 2], [datetime.datetime(2015, 2, 15), 1, 2], [datetime.datetime(2015, 2, 28), 1, 2], [datetime.datetime(2015, 3, 1), 1, 3], [datetime.datetime(2015, 3, 17), 1, 3], [datetime.datetime(2015, 3, 31), 1, 3]] df = pd.dataframe(table, columns=['date', 'id', 'value'])
how find first element of column value
, assign separate column in df
grouped id
? such df
like
date id value first 0 2015-01-01 1 0.5 0.5 1 2015-01-27 1 0.5 0.5 2 2015-01-31 1 0.5 0.5 3 2015-02-01 1 2.0 0.5 4 2015-02-03 1 2.0 0.5 5 2015-02-15 1 2.0 0.5 6 2015-02-28 1 2.0 0.5 7 2015-03-01 1 3.0 0.5 8 2015-03-17 1 3.0 0.5 9 2015-03-31 1 3.0 0.5
this seems easy problem, can't figure out solution. grateful suggestions, thanks.
you can group on 'id' column, call first
return first value group, returns series 'id' index, can call map
on orig df 'id' column perform lookup , assign corresponding value each 'id':
in [127]: df['first'] = df['id'].map(df.groupby('id')['value'].first()) df out[127]: date id value first 0 2015-01-01 1 0.5 0.5 1 2015-01-27 1 0.5 0.5 2 2015-01-31 1 0.5 0.5 3 2015-02-01 1 2.0 0.5 4 2015-02-03 1 2.0 0.5 5 2015-02-15 1 2.0 0.5 6 2015-02-28 1 2.0 0.5 7 2015-03-01 1 3.0 0.5 8 2015-03-17 1 3.0 0.5 9 2015-03-31 1 3.0 0.5
output first
:
in [128]: df.groupby('id')['value'].first() out[128]: id 1 0.5 name: value, dtype: float64
Comments
Post a Comment