Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将值添加到索引对象的末尾_Python_Pandas - Fatal编程技术网

Python 将值添加到索引对象的末尾

Python 将值添加到索引对象的末尾,python,pandas,Python,Pandas,我有一个熊猫索引对象,我想在它的末尾添加一个值。.append()方法的工作方式似乎与预期不同,而且由于我正在尝试添加元素,因此无法在-1位置插入,因为这会将值放在倒数第二位。比如说 import pandas as pd ser = pd.Series([1,2,3,4,5], index=[11,12,13,14,15]) indx = ser.index 假设我想在索引的末尾加上值20。这会引发一个错误: indx.append(20) 返回[11,12,13,14,20,15]: i

我有一个熊猫索引对象,我想在它的末尾添加一个值。.append()方法的工作方式似乎与预期不同,而且由于我正在尝试添加元素,因此无法在-1位置插入,因为这会将值放在倒数第二位。比如说

import pandas as pd
ser = pd.Series([1,2,3,4,5], index=[11,12,13,14,15])
indx = ser.index
假设我想在索引的末尾加上值20。这会引发一个错误:

indx.append(20)
返回[11,12,13,14,20,15]:

indx.insert(-1, 20)
这是可行的,但似乎是一个解决方案:

indx.insert(len(indx), 20)

有什么我遗漏的吗?这是在熊猫0.18.1上。谢谢。

方法
append
将另一个索引作为输入,但如果您只需传递一个类似数组的对象,该方法将起作用:

indx.union([20])

请注意,pandas中的索引对象是不可变的,因此任何此类操作都将返回一个新索引,而不是修改现有索引。

在附加到给定的
索引对象时,您需要将一组索引值作为参数传递

indx.append(pd.Index([20]))   # Pass the values inside the list 
Int64Index([11, 12, 13, 14, 15, 20], dtype='int64')

您可能需要尝试以下两个选项:

import pandas as pd
import numpy as np
ser.append(pd.Series([np.nan], index = [20]))

# 11    1.0
# 12    2.0
# 13    3.0
# 14    4.0
# 15    5.0
# 20    NaN
# dtype: float64

ser.set_value(20, np.nan)

# 11    1.0
# 12    2.0
# 13    3.0
# 14    4.0
# 15    5.0
# 20    NaN
# dtype: float64

如果你的目标是扩展序列而不是索引本身,你应该使用这个答案。我喜欢这个答案,因为它比创建一个要附加的新索引要短,但是新值是在开始而不是结束时添加的。这个方法不保留索引中值的顺序。