Add a column value depending on a date range (if-else)

送分小仙女□ 提交于 2021-02-10 17:54:10

问题


I have a date column in my dataframe and want to add a column called location. The value of location in each row should depend on which date range it falls under.

For example, the date 13th November falls between 12th November and 16th November & therefore the location should be Seattle. The date 17th November falls between 17th November and 18th November and must be New York.

Below is an example of the data frame I want to achieve

Dates     | Location (column I want to add)
.............................................
11/12/2017| Seattle
11/13/2017| Seattle
11/14/2017| Seattle
11/15/2017| Seattle
11/16/2017| Seattle
11/17/2017| New York
11/18/2017| New York
11/19/2017| London
11/20/2017| London

回答1:


Create dictionary of locations with start and end dates first, then loop by dict and set values by loc and between:

d = {'Seattle':['2017-11-12','2017-11-16'],
     'New York':['2017-11-17','2017-11-18'],
     'London':['2017-11-19','2017-11-20']}

df['Dates'] = pd.to_datetime(df['Dates'], format='%m/%d/%Y')

for k, (s,e) in d.items():
    df.loc[df['Dates'].between(s,e), 'Loc'] = k

print (df)
       Dates  Location       Loc
0 2017-11-12   Seattle   Seattle
1 2017-11-13   Seattle   Seattle
2 2017-11-14   Seattle   Seattle
3 2017-11-15   Seattle   Seattle
4 2017-11-16   Seattle   Seattle
5 2017-11-17  New York  New York
6 2017-11-18  New York  New York
7 2017-11-19    London    London
8 2017-11-20    London    London

EDIT:

d = {'Seattle':[('2017-11-12','2017-11-13'), ('2017-11-15','2017-11-16')],
     'New York':[('2017-11-17','2017-11-18')],
     'London':[('2017-11-19','2017-11-20'), ('2017-11-14','2017-11-14')]}

df['Dates'] = pd.to_datetime(df['Dates'], format='%m/%d/%Y')

for k, v in d.items():
    for s, e in v:
        df.loc[df['Dates'].between(s,e), 'Loc'] = k

print (df)
       Dates  Location       Loc
0 2017-11-12   Seattle   Seattle
1 2017-11-13   Seattle   Seattle
2 2017-11-14   Seattle    London
3 2017-11-15   Seattle   Seattle
4 2017-11-16   Seattle   Seattle
5 2017-11-17  New York  New York
6 2017-11-18  New York  New York
7 2017-11-19    London    London
8 2017-11-20    London    London


来源:https://stackoverflow.com/questions/53553557/add-a-column-value-depending-on-a-date-range-if-else

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!