如何更改 Pandas 系列的索引值
How do I change the index values of a Pandas Series
(对不起,如果这个问题很愚蠢或不清楚,我是编程新手)
我想知道如何将 Pandas 系列的索引值从它们默认的常规整数值更改为我拥有的列表中的值。
例如
x = pd.Series([421, 122, 275, 847, 175])
index_values = ['2014-01-01', '2014-01-02', '2014-01-03', '2014-01-04',
'2014-01-05']
如何让 index_values
列表中的日期成为我创建的系列中的索引 x
您可以通过list
分配索引值:
x.index = index_values
print(x)
2014-01-01 421
2014-01-02 122
2014-01-03 275
2014-01-04 847
2014-01-05 175
dtype: int64
set_axis
要更改现有系列的索引,请使用 set_axis
:
x = x.set_axis(index_values)
# 2014-01-01 421
# 2014-01-02 122
# 2014-01-03 275
# 2014-01-04 847
# 2014-01-05 175
# dtype: int64
相对于 x.index = index_values
的优势:
方法链接
x.some_method().set_axis(index_values).another_method()
错误检查
x.set_axis(list('abcdefg')) # ValueError: Length mismatch (Series:5, Index:7)
x.index = list('abcdefg') # No error despite mismatch
index
参数
如果您要创建新系列,请在创建时使用 index
参数:
x = pd.Series([421, 122, 275, 847, 175], index=index_values)
(对不起,如果这个问题很愚蠢或不清楚,我是编程新手)
我想知道如何将 Pandas 系列的索引值从它们默认的常规整数值更改为我拥有的列表中的值。 例如
x = pd.Series([421, 122, 275, 847, 175])
index_values = ['2014-01-01', '2014-01-02', '2014-01-03', '2014-01-04',
'2014-01-05']
如何让 index_values
列表中的日期成为我创建的系列中的索引 x
您可以通过list
分配索引值:
x.index = index_values
print(x)
2014-01-01 421
2014-01-02 122
2014-01-03 275
2014-01-04 847
2014-01-05 175
dtype: int64
set_axis
要更改现有系列的索引,请使用 set_axis
:
x = x.set_axis(index_values)
# 2014-01-01 421
# 2014-01-02 122
# 2014-01-03 275
# 2014-01-04 847
# 2014-01-05 175
# dtype: int64
相对于 x.index = index_values
的优势:
方法链接
x.some_method().set_axis(index_values).another_method()
错误检查
x.set_axis(list('abcdefg')) # ValueError: Length mismatch (Series:5, Index:7)
x.index = list('abcdefg') # No error despite mismatch
index
参数
如果您要创建新系列,请在创建时使用 index
参数:
x = pd.Series([421, 122, 275, 847, 175], index=index_values)