在Pandas中改变一个系列的索引顺序
假设我们想改变系列的索引顺序,那么我们必须使用pandas模块的Series.reindex()方法来执行这一任务。
Series ,它是一个能够容纳任何数据的一维标签阵列。
语法: pandas.Series(data, index, dtype, copy)
参数:
- data: 需要ndarrys, list, constants。
- index: 指数值。
- dtypes:为数据类型。
- copy:复制数据,默认为False。
Series.reindex()方法,用于在索引的基础上改变数据。
语法: Series.reindex(labels=None, index=None, columns=None, axis=None, method=None, copy=True, level=None, fill_value=nan, limit=None, tolerance=None)
让我们创建一个系列。
# 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
输出:
Series
示例 1:
# 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:
# 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
输出: