反转 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