简体   繁体   中英

assign series values based on index

having a simple series:

>>> s = pd.Series(index=pd.date_range('2016-09-01','2016-09-05'))
>>> s

2016-09-01   NaN
2016-09-02   NaN
2016-09-03   NaN
2016-09-04   NaN
2016-09-05   NaN
Freq: D, dtype: float64

Am I able to set series values based on its index? Let's say, I want to set series values to dayofweek of corresponding index entry. Of course, I can accomplish it easily by constructing series from scratch:

>>> dr = pd.date_range('2016-09-01','2016-09-05')
>>> s = pd.Series(data=dr.dayofweek, index=dr)
>>> s

2016-09-01    3
2016-09-02    4
2016-09-03    5
2016-09-04    6
2016-09-05    0
Freq: D, dtype: int32

I am also able to accomplish it using dataframe: df['old_column'] = df.index.dayofweek . Is it possible to set series in similar manner (using the only "column" series have)? .apply() and .map() methods seem as no help, since they do not work with index values...

You can do it like this:

s[s.index] = s.index.dayofweek

s
Out: 
2016-09-01    3
2016-09-02    4
2016-09-03    5
2016-09-04    6
2016-09-05    0
Freq: D, dtype: int32

When using apply on a series, you cannot access the index values. However, you can when using apply on a dataframe. So, convert to a dataframe first.

s.to_frame().apply(lambda x: x.name.dayofweek, axis=1)

2016-09-01    3
2016-09-02    4
2016-09-03    5
2016-09-04    6
2016-09-05    0
Freq: D, dtype: int64

This is a demonstration of how to access the index value via apply . If assigning a column to be the dayofweek values is the only objective, s.index.dayofweek is far more appropriate.

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