当index未知且列中的值是唯一的时,替换pandas数据帧中的单个值

时间:2017-05-27 14:33:00

标签: python pandas

a question on SO with the title "Set value for particular cell in pandas DataFrame",但它假定行索引已知。如果相关列中的行值是唯一的,如何更改值?使用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

1 个答案:

答案 0 :(得分:4)

无论性能如何,您都可以使用loc boolean 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