当索引未知且列中的值唯一时,替换熊猫数据框中的单个值


问题内容

以“大熊猫中的数据帧设定值特定的细胞”的称号上SO一个问题,但它假定行索引是已知的。如果相关列中的行值是唯一的,如何更改值?下面是使用set_index最简单的选项吗?用index.tolist返回索引值列表似乎不是一个很好的解决方案。

这是我的代码:

import pandas as pd

## Fill the data frame.
df = pd.DataFrame([[1, 2], [3, 4]], columns=('a', 'b'))
print(df, end='\n\n')

## Just use the index, if we know it.
index = 0
df.set_value(index, 'a', 5)
print('set_value', df, sep='\n', end='\n\n')

## Define a new index column.
df.set_index('a', inplace=True)
print('set_index', df, sep='\n', end='\n\n')

## Use the index values of column A, which are known to us.
index = 3
df.set_value(index, 'b', 6)
print('set_value', df, sep='\n', end='\n\n')

## Reset the index.
df.reset_index(inplace = True)
print('reset_index', df, sep='\n')

这是我的输出:

   a  b
0  1  2
1  3  4

set_value
   a  b
0  5  2
1  3  4

set_index
   b
a   
5  2
3  4

set_value
   b
a   
5  2
3  6

reset_index
   a  b
0  5  2
1  3  6

问题答案:

不管表现,你应该能够做到这一点使用locboolean indexing

df = pd.DataFrame([[5, 2], [3, 4]], columns=('a', 'b'))

# modify value in column b where a is 3
df.loc[df.a == 3, 'b'] = 6

df
#   a   b
#0  5   2
#1  3   6