python - Pandas :按位置访问的索引更新和更改值

标签 python indexing pandas dataframe

我有两个关于 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) 我希望能够将 df 的第 5 个元素的 B 列设置为“三”。但是 df.iloc[5]['B'] = 'three' 不会那样做。我检查了 manual但它不包括如何更改按位置访问的特定单元格值。

如果我按行名访问,我可以这样做:df.loc[5,'B'] = 'three' 但我不知道等效的索引访问是什么。

附言Link1link2是我第二个问题的相关答案。但是,他们没有回答我的问题。

最佳答案

1) I do not understand why the indexing is not automatically updated after I modify the dataframe.

如果你想在删除/添加行后重置索引,你可以这样做:

df = df[df.B != 'three'] # remove where B = three
df.reset_index(drop=True)

       B    amount  id
0    one    -1.176137    1
1    one     0.434470    2
2    two    -0.887526    3
3    two     0.126969    5
4    one     0.090442    7
5    two    -1.511353    8

索引用于标记/标记/标识一行...因此您可能会考虑将“id”列作为索引,然后您会明白 Pandas 在删除时不会“自动更新”索引行。

df.set_index('id')

       B    amount
id      
1    one    -0.410671
2    one     0.092931
3    two    -0.100324
4    three   0.322580
5    two    -0.546932
6    three  -2.018198
7    one    -0.459551
8    two     1.254597

2) I want to be able to set the B column of the 5th element of df to 'three'. But df.iloc[5]['B'] = 'three' does not do that. I checked on the manual but it does not cover how to change a specific cell value accessed by location.

Jeff 已经回答了这个...

关于python - Pandas :按位置访问的索引更新和更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20997082/

相关文章:

python - 从 Pandas DataFrame 绘图时控制颜色、图例,每个 x 有多个 y 值

mysql - 如何优化 MySQL 索引/查询以进行模块化搜索?

矩阵无法索引

mysql - 子查询(以及带有连接的查询)不使用 MySQL 索引 (MyISAM)

python - 使用 Pandas 向 csv 文件添加独立标题

python - 如何为 pandas 数据框行中的每个新分组分配数值?

python - 在 while(1) 循环中生成文件编号序列

python - 有没有办法修复 vim 没有注意到 python if 语句有注释?

python - cx_卡住 : LookupError: unknown encoding: cp437

python - 如何在 Python 网站中查找未使用的代码?