反轉 Pandas 資料框的行?
我們將在此處瞭解如何反轉 Pandas 資料框的行。Pandas 是一個開源的 Python 庫,它使用強大的資料結構提供高效能的資料操作和分析工具。資料框是一個二維資料結構,即資料以表格形式在行和列中對齊。
使用索引反轉 Pandas 資料框的行
示例
在這個示例中,我們將使用 `[::-1]` 反轉資料框的行。
import pandas as pd # Create a Dictionary dct = {'Rank':[1,2,3,4,5], 'Points':[100,87, 80,70, 50]} # Create a DataFrame from Dictionary elements using pandas.dataframe() df = pd.DataFrame(dct) print("DataFrame = \n",df) # Reverse the DataFrame using indexing print("\nReverse the DataFrame = \n",df[::-1])
輸出
DataFrame =
Rank Points
0 1 100
1 2 87
2 3 80
3 4 70
4 5 50
Reverse the DataFrame =
Rank Points
4 5 50
3 4 70
2 3 80
1 2 87
0 1 100
使用 `reindex()` 反轉 Pandas 資料框的行
示例
在這個示例中,我們將使用 `reindex()` 方法反轉資料框的行。
import pandas as pd # Create a Dictionary dct = {'Rank':[1,2,3,4,5], 'Points':[100,87, 80,70, 50]} # Create a DataFrame from Dictionary elements using pandas.dataframe() df = pd.DataFrame(dct) print("DataFrame = \n",df) # Reverse the DataFrame using reindex() print("\nReverse the DataFrame = \n",df.reindex(index=df.index[::-1]))
輸出
DataFrame =
Rank Points
0 1 100
1 2 87
2 3 80
3 4 70
4 5 50
Reverse the DataFrame =
Rank Points
4 5 50
3 4 70
2 3 80
1 2 87
0 1 100
使用 `iloc` 反轉 Pandas 資料框的行
示例
在這個示例中,我們將使用 `iloc` 方法反轉資料框的行。
import pandas as pd # Create a Dictionary dct = {'Rank':[1,2,3,4,5], 'Points':[100,87, 80,70, 50]} # Create a DataFrame from Dictionary elements using pandas.dataframe() df = pd.DataFrame(dct) print("DataFrame = \n",df) # Reverse the DataFrame using iloc print("\nReverse the DataFrame = \n",df.iloc[::-1])
輸出
DataFrame =
Rank Points
0 1 100
1 2 87
2 3 80
3 4 70
4 5 50
Reverse the DataFrame =
Rank Points
4 5 50
3 4 70
2 3 80
1 2 87
0 1 100
使用 `sort_index()` 反轉 Pandas 資料框的行
示例
在這個示例中,我們將使用 `sort_index()` 方法反轉資料框的行。在引數中,我們可以設定順序,即升序 False 或 True。
import pandas as pd # Create a Dictionary dct = {'Rank':[1,2,3,4,5], 'Points':[100,87, 80,70, 50]} # Create a DataFrame from Dictionary elements using pandas.dataframe() df = pd.DataFrame(dct) print("DataFrame = \n",df) # Reverse the DataFrame using sort_index() print("\nReverse the DataFrame = \n",df.sort_index(ascending=False))
輸出
DataFrame =
Rank Points
0 1 100
1 2 87
2 3 80
3 4 70
4 5 50
Reverse the DataFrame =
Rank Points
4 5 50
3 4 70
2 3 80
1 2 87
0 1 100
使用 `reset_index()` 反轉 Pandas 資料框的行
示例
在這裡,我們將看到另一種反轉 DataFrame 行的方法。這也會在反轉 DataFrame 後重置索引。讓我們看看示例。
import pandas as pd # Create a Dictionary dct = {'Rank':[1,2,3,4,5], 'Points':[100,87, 80,70, 50]} # Create a DataFrame from Dictionary elements using pandas.dataframe() df = pd.DataFrame(dct) print("DataFrame = \n",df) # Reverse the DataFrame using reset_index() print("\nReverse the DataFrame = \n",df[::-1].reset_index())
輸出
DataFrame =
Rank Points
0 1 100
1 2 87
2 3 80
3 4 70
4 5 50
Reverse the DataFrame =
index Rank Points
0 4 5 50
1 3 4 70
2 2 3 80
3 1 2 87
4 0 1 100
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP