怎么在dataframe中限定index的值同时输出这些切片中最大的值,同时输出对应的行上的值
时间: 2023-06-11 12:07:24 浏览: 35
可以使用 Pandas 的 loc 方法来限定 index 的值,并使用 max 和 idxmax 方法来找到最大值及其对应的行。
假设有如下的 DataFrame:
```
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie', 'David', 'Emily'],
'age': [25, 30, 35, 40, 45],
'salary': [5000, 6000, 7000, 8000, 9000]
}, index=['a', 'b', 'c', 'd', 'e'])
print(df)
```
输出:
```
name age salary
a Alice 25 5000
b Bob 30 6000
c Charlie 35 7000
d David 40 8000
e Emily 45 9000
```
如果要限定 index 的值为 `['b', 'c', 'd']`,并输出这些行中 salary 最大的值及其对应的行上的值,可以使用以下代码:
```
sliced_df = df.loc[['b', 'c', 'd']]
max_salary = sliced_df['salary'].max()
max_salary_row = sliced_df.loc[sliced_df['salary'].idxmax()]
print('Max salary:', max_salary)
print('Row with max salary:')
print(max_salary_row)
```
输出:
```
Max salary: 8000
Row with max salary:
name David
age 40
salary 8000
Name: d, dtype: object
```
其中,`df.loc[['b', 'c', 'd']]` 返回了 index 为 `['b', 'c', 'd']` 的行切片;`sliced_df['salary'].max()` 返回了这些行中 salary 的最大值;`sliced_df.loc[sliced_df['salary'].idxmax()]` 返回了 salary 最大的行。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)