2017-05-27 48 views
0

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

无论性能,你应该能够做到这一点使用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 
+0

谢谢!我刚刚在其他问题线程中找到了相同的答案。它只有很少的选票。 https://stackoverflow.com/a/38467449/778533 –

+0

@ tommy.carstensen这是一个非常近期的答案,几乎在问题提出四年后才被问到。 :) – Psidom

相关问题