繁体   English   中英

根据索引分配序列值

[英]assign series values based on index

有一个简单的系列:

>>> 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

我可以根据其索引设置序列值吗? 假设我想将系列值设置为相应索引条目的dayofweek。 当然,我可以通过从头开始构建系列轻松完成此操作:

>>> 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

我也可以使用df['old_column'] = df.index.dayofweek来完成它: df['old_column'] = df.index.dayofweek 是否可以以类似的方式设置系列(使用唯一的“列”系列)? .apply().map()方法似乎无济于事,因为它们不适用于索引值...

您可以这样做:

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

在系列上使用apply时,无法访问索引值。 但是,您可以使用时, apply上的数据帧。 因此,请先转换为数据框。

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

这演示了如何通过apply访问索引值。 如果将列dayofweek为“ s.index.dayofweek值是唯一目标,则s.index.dayofweek更为合适。

暂无
暂无

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

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