[英]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.