excel - Python VLOOKUP based on dates - Pandas -
having issue pandas df, trying "count" column based on date, code should search "date range' within dates column, , if present 'count' should copied "posts" column corresponding date eg: date_range value = 16/02/2017 - code searches 16/02/2017 in "dates" column , makes "posts" equal "count" value of date - if date_range value not appear - posts should = 0.
data example:
dates count date_range posts 0 07/02/2017 1 16/12/2016 (should = 5) 1 01/03/2017 1 17/12/2016 2 15/02/2017 1 18/12/2016 3 23/01/2017 1 19/12/2016 4 28/02/2017 1 20/12/2016 5 09/02/2017 2 21/12/2016 6 20/03/2017 2 22/12/2016 7 16/12/2016 5 my code looks this:
datelist = df['dates'].tolist() date in df['date_range']: if str(date) in datelist: df['posts'] = df['count'] else: dates_df['posts'] = 0 however makes data map wrong values "posts"
hopefully explained correctly! in advance help!
you can first create dict matching values , map date_range column:
print (df) dates count date_range 0 07/02/2017 1 16/12/2016 1 01/03/2017 1 17/12/2016 2 15/02/2017 1 18/12/2016 3 23/01/2017 1 19/12/2016 4 28/02/2017 1 07/02/2017 <-change value match 5 09/02/2017 2 21/12/2016 6 20/03/2017 2 22/12/2016 7 16/12/2016 5 22/12/2016 d = df[df['dates'].isin(df.date_range)].set_index('dates')['count'].to_dict() print (d) {'16/12/2016': 5, '07/02/2017': 1} df['posts'] = df['date_range'].map(d).fillna(0).astype(int) print (df) dates count date_range posts 0 07/02/2017 1 16/12/2016 5 1 01/03/2017 1 17/12/2016 0 2 15/02/2017 1 18/12/2016 0 3 23/01/2017 1 19/12/2016 0 4 28/02/2017 1 07/02/2017 1 5 09/02/2017 2 21/12/2016 0 6 20/03/2017 2 22/12/2016 0 7 16/12/2016 5 22/12/2016 0
Comments
Post a Comment