pandas找到某元素的行数
时间: 2023-05-09 21:01:41 浏览: 335
在使用Pandas时,有时我们需要找到某个元素在DataFrame中的行数。以下是两种简单的方法:
1. 使用loc方法
Pandas提供了loc方法,可以通过元素的值进行定位。例如,我们要找到DataFrame中值为10的元素所在的行数:
```
import pandas as pd
# 创建DataFrame
df = pd.DataFrame({'A': [1, 5, 10, 15], 'B': [2, 6, 11, 16]})
# 找到元素所在的行数
row_num = df.loc[df['A'] == 10].index[0]
print(row_num)
```
输出结果为:
```
2
```
这表示值为10的元素在DataFrame的第3行。
2. 使用numpy.where方法
另一种方法是使用numpy库中的where方法,它可以在数组中查找元素的索引。首先将DataFrame转换为numpy数组,然后使用where方法查找元素的索引。例如,我们要找到值为10的元素在DataFrame中的行数:
```
import pandas as pd
import numpy as np
# 创建DataFrame
df = pd.DataFrame({'A': [1, 5, 10, 15], 'B': [2, 6, 11, 16]})
# 转换为numpy数组
arr = np.array(df)
# 使用where方法查找元素的索引
row_num = np.where(arr == 10)[0][0]
print(row_num)
```
输出结果为:
```
2
```
这也表示值为10的元素在DataFrame的第3行。
以上是两种简单的方法来找到DataFrame中某个元素的行数。
阅读全文
相关推荐















