Pandas 中如何获取特定列满足给定条件的所有行的索引
我们可以使用简单的索引操作获得特定列满足给定条件的所有行的索引。我们还可以使用 NumPy 包中的 where()
方法和 DataFrame 对象的 query()
方法找到它们的索引。
简单的索引操作可获取 Pandas 中特定列满足给定条件的所有行的索引
使用简单的索引操作可以完成获取特定列满足给定条件的行的索引的任务。
import pandas as pd
import numpy as np
dates = ["April-10", "April-11", "April-12", "April-13", "April-14", "April-16"]
sales = [200, 300, 400, 200, 300, 300]
prices = [3, 1, 2, 4, 3, 2]
df = pd.DataFrame({"Date": dates, "Sales": sales, "Price": prices})
reqd_Index = df[df["Sales"] >= 300].index.tolist()
print(reqd_Index)
输出:
[1, 2, 4, 5]
这里,df['Sales']>=300
给出一系列布尔值,如果其 Sales
列的值大于或等于 300,则其元素为 True。
我们可以通过使用 df[df['Sales']>=300].index
来检索销售值大于或等于 300 的行的索引。
最后,tolist()
方法将所有索引转换为列表。
np.where()
方法获取特定列满足给定条件的所有行的索引
np.where()
将条件作为输入,并返回满足给定条件的元素的索引。因此,我们可以使用 np.where()
来获取特定列满足给定条件的所有行的索引。
import pandas as pd
import numpy as np
dates = ["April-10", "April-11", "April-12", "April-13", "April-14", "April-16"]
sales = [200, 300, 400, 200, 300, 300]
prices = [3, 1, 2, 4, 3, 2]
df = pd.DataFrame({"Date": dates, "Sales": sales, "Price": prices})
reqd_Index = list(np.where(df["Sales"] >= 300))
print(reqd_Index)
输出:
[array([1, 2, 4, 5])]
这将输出 Sales
列中的值大于或等于 300
的所有行的索引。
pandas.DataFrame.query()
获取特定列满足给定条件的所有行的索引
pandas.DataFrame.query() 返回由提供的查询表达式产生的 DataFrame。现在,我们可以使用 DataFrame 的 index 属性返回其特定列满足给定条件的所有行的索引。
import pandas as pd
import numpy as np
dates = ["April-10", "April-11", "April-12", "April-13", "April-14", "April-16"]
sales = [200, 300, 400, 200, 300, 300]
prices = [3, 1, 2, 4, 3, 2]
df = pd.DataFrame({"Date": dates, "Sales": sales, "Price": prices})
reqd_index = df.query("Sales == 300").index.tolist()
print(reqd_index)
输出:
[1, 4, 5]
它返回特定列满足给定条件 Sales == 300
的所有行的索引列表。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串