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

Python 当索引未知且列中的值唯一时,替换数据帧中的单个值,python,pandas,Python,Pandas,有,但它假定行索引已知。如果相关列中的行值是唯一的,如何更改值?使用下面的方法是最简单的选择吗?使用返回索引值列表似乎不是一个非常优雅的解决方案 这是我的密码: 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 =

有,但它假定行索引已知。如果相关列中的行值是唯一的,如何更改值?使用下面的方法是最简单的选择吗?使用返回索引值列表似乎不是一个非常优雅的解决方案

这是我的密码:

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

无论性能如何,您都应该能够使用
loc
布尔索引来执行此操作:

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

谢谢我刚才在另一个问题线索中找到了相同的答案。它只有很少的选票@汤米·卡斯滕森这是一个非常新的答案,差不多是在这个问题被首次提出四年后