我有两个关于 Python Pandas 数据框的索引相关问题。
import pandas as pd
import numpy as np
df = pd.DataFrame({'id' : range(1,9),
'B' : ['one', 'one', 'two', 'three',
'two', 'three', 'one', 'two'],
'amount' : np.random.randn(8)})
df = df.ix[df.B != 'three'] # remove where B = three
df.index
>> Int64Index([0, 1, 2, 4, 6, 7], dtype=int64) # the original index is preserved.
1)我不明白为什么修改数据框后索引不会自动更新。有没有办法在修改数据框时自动更新索引?如果没有,最有效的手动方法是什么?
2)我希望能够设置B
第 5 个元素的列df
到“三”。但df.iloc[5]['B'] = 'three'
不这样做。我检查了manual http://pandas.pydata.org/pandas-docs/dev/indexing.html#indexing-integer但它不包括如何更改通过位置访问的特定单元格值。
如果我按行名称访问,我可以这样做:df.loc[5,'B'] = 'three'
但我不知道索引访问等效项是什么。
P.S. Link1 https://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe and link2 https://stackoverflow.com/questions/17729853/set-value-for-a-selected-cell-in-pandas-dataframe?lq=1是我的第二个问题的相关答案。但是,他们没有回答我的问题。