简体   繁体   English

根据索引分配序列值

[英]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. 假设我想将系列值设置为相应索引条目的dayofweek。 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 . 我也可以使用df['old_column'] = df.index.dayofweek来完成它: 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... .apply().map()方法似乎无济于事,因为它们不适用于索引值...

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. 在系列上使用apply时,无法访问索引值。 However, you can when using apply on a dataframe. 但是,您可以使用时, apply上的数据帧。 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 . 这演示了如何通过apply访问索引值。 If assigning a column to be the dayofweek values is the only objective, s.index.dayofweek is far more appropriate. 如果将列dayofweek为“ s.index.dayofweek值是唯一目标,则s.index.dayofweek更为合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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