更改 Pandas 中系列的索引顺序
假设我们想改变系列的索引顺序,那么我们必须使用 pandas 模块的Series.reindex()方法来执行这个任务。
Series ,它是一个能够保存任何数据的一维标记数组。
Syntax: pandas.Series(data, index, dtype, copy)
Parameters:
- data takes ndarrys, list, constants.
- index values.
- dtypes for data types.
- Copy data, default is False.
要了解更多关于熊猫系列的信息,请单击此处。
Series.reindex()方法 用于根据索引更改数据。
Syntax: Series.reindex(labels=None, index=None, columns=None, axis=None, method=None, copy=True, level=None, fill_value=nan, limit=None, tolerance=None)
要了解有关 pandas Series.reindex() 方法的更多信息,请单击此处。
让我们创建一个系列:
Python3
# import required library
import pandas as pd
import numpy as np
# create numpy array
data = np.array(["Android dev",
"content writing",
"competitive coding"])
#create a series
total_series = pd.Series(data,
index = [1, 2, 3])
# show the series
total_series
Python3
# import required library
import pandas as pd
import numpy as np
# create numpy array
data = np.array(["Android dev",
"content writing",
"competitive coding"])
# create a series
total_series = pd.Series(data,
index = [1, 2, 3])
# reindexing of series
total_series = total_series.reindex(index
= [3, 2, 1])
# show the series
total_series
Python3
# import required library
import pandas as pd
import numpy as np
# create numpy array
data = np.array(["Android dev",
"content writing",
"competitive coding"])
# create a series
total_series = pd.Series(data,
index = [1, 2, 3])
# reindexing of series
total_series = total_series.reindex([2, 3, 1])
# show the series
total_series
输出:
示例 1:
Python3
# import required library
import pandas as pd
import numpy as np
# create numpy array
data = np.array(["Android dev",
"content writing",
"competitive coding"])
# create a series
total_series = pd.Series(data,
index = [1, 2, 3])
# reindexing of series
total_series = total_series.reindex(index
= [3, 2, 1])
# show the series
total_series
输出:
示例 2:
Python3
# import required library
import pandas as pd
import numpy as np
# create numpy array
data = np.array(["Android dev",
"content writing",
"competitive coding"])
# create a series
total_series = pd.Series(data,
index = [1, 2, 3])
# reindexing of series
total_series = total_series.reindex([2, 3, 1])
# show the series
total_series
输出: