iT邦幫忙

2025 iThome 鐵人賽

DAY 15
0
佛心分享-讓我升級的那些書

菜雞學習 pandas 的 30 日讀書分享系列 第 15

菜雞學習 pandas 的 30 日讀書分享【Day 15】reindex (重設索引) 上

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20250813/20168290vDADyiEnWE.jpg

reindex (重設索引) 上

reindex 是 pandas 物件的重要方法,將一個物件裡的值按照指定的索引重新排序並產生一個新物件。

In [98]: obj = pd.Series([4.5, 7.2, -5.3, 3.6], index=["d", "b", "a", "c"])

In [99]: obj
Out[99]: obj
d    4.5
b    7.2
a   -5.3
c    3.6
dtypeL float64

對著 Series 呼叫 reindex 會按照新索引來重新排列資料,如果物件沒有指定的索引值,則會加入 NaN:

In [100]: obj2 = obj.reindex(["a", "b", "c", "d", "e"])

In [101]: obj2
Out[101]:
a   -5.3
b    7.2
c    3.6
d    4.5
e    NaN
dtype: float64

如果資料是有序的,例如時間序列,可能想要在做 reindex 的時候做一些填值,可以使用 method 選項與 ffill 等方法來做這件事:

In [102]: obj3 = pd.Series(["blue", "purple", "yellow"], index=[0, 2, 4])
 
In [103]: obj3
Out[103]:
0      blue
2    purple
4    yellow
dtype: object
 
In [104]: obj3.reindex(np.arange(6), method="ffill")
Out[104]:
0      blue
1      blue
2    purple
3    purple
4    yellow
5    yellow
dtype: object

對著 DataFrame 使用 reindex 可能會修改索引、欄、列,如果只傳入序列,則會 reindex 橫列:

In [105]: frame = pd.DataFrame(np.arange(9).reshape((3,3)),
                                  index=["a", "c", "d"],
                                  columns=["Ohio", "Texas", "California"])
In [106]: frame
Out[106]:
   Ohio  Texas   California
a     0      1            2
c     3      4            5
d     6      7            8

In [107]: frame2 = frame.reindex(index=["a", "b", "c", "d"])

In [108]: frame2
Out[108]:
   Ohio  Texas  California
a   0.0    1.0         2.0
b   NaN    NaN         NaN
c   3.0    4.0         5.0
d   6.0    7.0         8.0

今日的分享就到這囉,我們明天見,掰掰!


上一篇
菜雞學習 pandas 的 30 日讀書分享【Day 14】Index 物件
下一篇
菜雞學習 pandas 的 30 日讀書分享【Day 16】reindex (重設索引) 下
系列文
菜雞學習 pandas 的 30 日讀書分享30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言