根据索引分配系列值
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
我可以根据索引设置系列值吗?
比方说,我想将系列值设置为相应索引条目的星期几。当然,我可以通过从头构建系列来轻松完成它:
>>> 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
。是否可以以类似的方式设置系列(使用唯一的 "column" 系列)? .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
值是唯一的 objective,则 s.index.dayofweek
更为合适。
有一个简单的系列:
>>> 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
我可以根据索引设置系列值吗? 比方说,我想将系列值设置为相应索引条目的星期几。当然,我可以通过从头构建系列来轻松完成它:
>>> 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
。是否可以以类似的方式设置系列(使用唯一的 "column" 系列)? .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
值是唯一的 objective,则 s.index.dayofweek
更为合适。