Pandas:如何访问索引的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19990782/
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
Pandas: How to access the value of the index
提问by Ross R
I have a dataframe and would like to use the values in the index to create another column.
For instance:
我有一个数据框,想使用索引中的值来创建另一列。
例如:
df=pd.DataFrame({'idx1':range(0,5), 'idx2':range(10000,10005), 'value':np.random.randn(5)})
df.set_index(keys=['idx1','idx2'], inplace=True)
print df
value
idx1 idx2
0 10000 -1.470367
1 10001 0.260693
2 10002 -0.732319
3 10003 -0.116977
4 10004 1.106644
I'd like to do something like this:
我想做这样的事情:
df['idx1_mod']= df['idx1'] + 100
(Actually, I want to do more complicated things, but basically I need the value of the index.)
(其实我想做更复杂的事情,但基本上我需要索引的值。)
Right now I'm resorting to reseting the index (to get the index fields as columns), doing my calcs with access to the columns, and then re-creating the index. I'm sure I'm missing something obvious, but I've looked a ton and keep missing it!
现在我正在求助于重置索引(将索引字段作为列),通过访问列进行计算,然后重新创建索引。我确定我错过了一些明显的东西,但我已经看了很多并且一直错过它!
Note - I also tried df.iterrows(), but it seems that gives a copy of the row and doesn't let me update the original dataframe.
注意 - 我也尝试过 df.iterrows(),但它似乎提供了该行的副本并且不允许我更新原始数据帧。
回答by HYRY
df["idx1_mod"] = df.index.get_level_values(0).values + 100
回答by simplemts
Try this:
尝试这个:
for idx in range(len(df)):
df['idx1_mod'][idx] = df.index[idx][0] + 100
回答by Tim
You can use drop=Falsewhen setting the index to preserve your keys as columns. This should work:
您可以drop=False在设置索引时使用以将键保留为列。这应该有效:
df.set_index(keys=['idx1','idx2'], inplace=True, drop=False)
df['idx1_mod'] = df['idx'] + 100

