Pandas Dataframe 行选择组合条件索引和列值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52169051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 06:00:01  来源:igfitidea点击:

Pandas Dataframe row selection combined condition index- and column values

pythonpandas

提问by Egirus Ornila

I want to select rows from a dataframe based on values in the index combined with values in a specific column:

我想根据索引中的值和特定列中的值从数据框中选择行:

df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [0, 20, 30], [40, 20, 30]], 
                  index=[4, 5, 6, 7], columns=['A', 'B', 'C'])


    A   B   C
4   0   2   3
5   0   4   1
6   0  20  30
7  40  20  30

with

df.loc[df['A'] == 0, 'C'] = 99

i can select all rows with column A = 0 and replace the value in column C with 99, but how can i select all rows with column A = 0 and the index < 6 (i want to combine selection on the index with selection on the column)?

我可以选择 A 列 = 0 的所有行并将 C 列中的值替换为 99,但是如何选择 A 列 = 0 且索引 < 6 的所有行(我想将索引上的选择与柱子)?

采纳答案by sacuL

You can use multiple conditions in your locstatement:

您可以在loc语句中使用多个条件:

df.loc[(df.index < 6) & (df.A == 0), 'C'] = 99