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

标签 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

最佳答案

无论性能如何,您都应该能够使用 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

关于python - 当索引未知且列中的值唯一时,替换 Pandas 数据框中的单个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44218091/

相关文章:

python windows 鼠标钩子(Hook)崩溃

Python:类型化方法参数

python自动邮件回复系统

python - 如何使用azureml中上传到pandas的数据集进行分析?

python - Pandas DateTime Apply 方法给出错误 '' Timestamp' 对象没有属性 'dt' '

python - 缩进 Notepad++ Python中制表符和空格的使用不一致

python - 我已经通过 macports 安装了 xapian,那么为什么这个 python 应用程序告诉我需要安装 xapian?

python - Pandas 生成具有值范围的数据框

python - 过滤 Pandas 数据框的行不起作用

python - 对一小时内出现的单元格进行分组 - Groupby