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