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 Data Frame的行
示例
在这个示例中,我们将使用iloc逆转一个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 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()方法来反转数据框的行。在参数中,我们可以设置order即升序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