python - 使用 loc 在 pandas 数据框中设置值 - 多个选择条件允许在不同列中设置值

标签 python pandas pandas-loc

我有一个包含多列和多行的数据库。我想在满足列子集的某些条件的数据库行中找到,如果它满足该条件,则更改同一行中不同列的值。
我正在使用以下数据库进行原型(prototype)设计

df = pd.DataFrame([[1, 2], [4, 5], [5, 5], [5, 9], [55, 55]], columns=['max_speed', 'shield'])
df['frcst_stus'] = 'current'
df
这给出了以下结果:
max_speed   shield  frcst_stus
0   1   2   current
1   4   5   current
2   5   5   current
3   5   9   current
4   55  55  current
我想将索引第 2 行更改为读取 5、5、'hello',而不更改数据帧的其余部分。
我可以在设置值时执行 Pandas.loc 文档中的示例。我可以设置与可调用条件匹配的行、列和行。但是电话是在单个专栏或系列上进行的。我要两个。
而且我发现了许多 stackoverflow 答案,这些答案使用 loc 在单个列上设置第二列中的值来回答问题。那不是我的问题。我想搜索两列数据。
以下允许我获得我想要的行:
result = df[(df['shield'] == 5) & (df['max_speed'] == 5) & (df['frcst_stus'] == 'current')]
而且我知道只是将等号 (== 'current') 更改为 (= 'current') 会给我一个错误。
当我在两列上选择时,我可以设置列(见下文),但两列都会设置。 ('arghh') 并且当我尝试测试 'max_speed' 的值时,我得到一个 false is not in index 错误。
df.loc[:, ['max_speed', 'frcst_stus']] = 'hello'
我在尝试解释 Python 的 bool 问题时也遇到了错误。坦率地说,我只是还不了解整个重载。

最佳答案

如果需要通过掩码 m 为两列设置不同的值:

m = (df['shield'] == 5) & (df['max_speed'] == 5) & (df['frcst_stus'] == 'current')

df.loc[m, ['max_speed', 'frcst_stus']] = [100, 'hello']

如果需要通过掩码 m 为两列设置相同的值:
df.loc[m, ['max_speed', 'frcst_stus']] = 'hello'

如果只需要设置一列掩码m :
df.loc[m, 'frcst_stus'] = 'hello'

关于python - 使用 loc 在 pandas 数据框中设置值 - 多个选择条件允许在不同列中设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58212270/

相关文章:

python - groupby 过滤每月余额均为负数的帐户

python - 使用 loc 删除索引过滤的数据框

python - Tensorflow tf.size 不适用于 tf.unique 的动态长度张量

python - 使用 Appium 和 Python 测试 iOS 应用程序时等待元素加载?

python - face_recognition.load_image_file ("{}"),这是什么意思?

python - 在 CSV 文件/Pandas Dataframe 中查找标题行的行号

python - 将列表传递给 pandas loc 方法

python - 如何更新 matplotlib hexbin 图?

python - 使用pandas读取rpt文件

python - 将当前行和上一行的差异附加到新列,用于多列