在 Pandas 索引对象的末尾添加一个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39230854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add a value to the end of a pandas index object
提问by Alex
I have a pandas index object and I'd like to add a single value to the end of it. The .append() method doesn't seem to work like one would expect, and since I'm trying to add an element, I can't insert at the location of -1 because that puts the value in the second-to-last position. For example
我有一个Pandas索引对象,我想在它的末尾添加一个值。.append() 方法似乎不像人们期望的那样工作,而且由于我正在尝试添加一个元素,因此我无法在 -1 的位置插入,因为这会将值放在第二个-最后一个位置。例如
import pandas as pd
ser = pd.Series([1,2,3,4,5], index=[11,12,13,14,15])
indx = ser.index
Say I want to add the value 20 to the end of the index. This throws an error:
假设我想将值 20 添加到索引的末尾。这会引发错误:
indx.append(20)
This returns [11,12,13,14,20,15]:
这将返回 [11,12,13,14,20,15]:
indx.insert(-1, 20)
This works but seems like a work-around:
这有效,但似乎是一种解决方法:
indx.insert(len(indx), 20)
Is there something I'm missing? This is on pandas 0.18.1. Thanks.
有什么我想念的吗?这是在Pandas 0.18.1 上。谢谢。
回答by Nickil Maveli
You need to pass a collection of index values as parameter while appending to the given index
object.
在附加到给定index
对象时,您需要将一组索引值作为参数传递。
indx.append(pd.Index([20])) # Pass the values inside the list
Int64Index([11, 12, 13, 14, 15, 20], dtype='int64')
回答by IanS
The method append
takes another index as input, but union
will work if you simply pass an array-like object:
该方法append
将另一个索引作为输入,但union
如果您只是传递一个类似数组的对象,它将起作用:
indx.union([20])
Note that index objects in pandas are immutable, so any such operation will return a new index rather than modifying the existing one.
请注意,pandas 中的索引对象是不可变的,因此任何此类操作都将返回一个新索引,而不是修改现有索引。
回答by Psidom
You may want to try these two options:
您可能想尝试以下两个选项:
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