Python pandas中是否有函数语法用于基于整数位置设置序列值?
假设我有序列Python pandas中是否有函数语法用于基于整数位置设置序列值?,python,pandas,functional-programming,Python,Pandas,Functional Programming,假设我有序列pd.series({'a':1,'b':2','c':3}),我想编辑第一个值,我可以调用pd.series({'a':1,'b':2,'c':3})。设置值('a',0) 是否有类似的函数接受整数位置而不是索引标签 也就是说,我想这样做 s = pd.Series({'a':1,'b':2,'c':3}).set_value(0,0) 还有一种方法可以使它不改变原始数据帧。我想我想要的是符合数据帧精神的东西。赋值,但它是按行操作的。您可以通过设置takeable=True来使用
pd.series({'a':1,'b':2','c':3})
,我想编辑第一个值,我可以调用pd.series({'a':1,'b':2,'c':3})。设置值('a',0)
是否有类似的函数接受整数位置而不是索引标签
也就是说,我想这样做
s = pd.Series({'a':1,'b':2,'c':3}).set_value(0,0)
还有一种方法可以使它不改变原始数据帧。我想我想要的是符合数据帧精神的东西。赋值,但它是按行操作的。您可以通过设置
takeable=True
来使用数字索引
s = pd.Series({'a':1,'b':2,'c':3}).set_value(0,0, takeable=True)
设置_值
改变原始数据帧或序列:
ser = pd.Series({'a':1,'b':2,'c':3})
new_ser = ser.set_value(0,0)
print(new_ser is ser)
True
您必须手动创建其副本:
ser = pd.Series({'a':1,'b':2,'c':3})
new_ser = ser.copy()
new_ser.set_value(0,0)
print(new_ser is ser)
False
要通过索引位置设置值,您可以使用@Batman指出的带takeable=True的set_value
。您也可以使用iat
(index at),它被明确设计为按索引位置引用值:
# create copy and set value via iat
new_ser = ser.copy()
new_ser.iat[0] = 0
在本例中,set\u value
的性能稍好一些:
%%timeit
new_ser = ser.copy()
new_ser.set_value(0,0, takeable=True)
10000 loops, best of 3: 53.4 µs per loop
这太晦涩了!
%%timeit
new_ser = ser.copy()
new_ser.iat[0] = 0
10000 loops, best of 3: 63.6 µs per loop