python写一个函数,将dataframe里的数据按所需行提取
时间: 2023-07-16 10:15:45 浏览: 188
pandas.dataframe按行索引表达式选取方法
5星 · 资源好评率100%
以下是一个示例函数,可以按所需行(行号从0开始)提取DataFrame中的数据:
```python
import pandas as pd
def extract_rows(df, rows):
"""
Extract specified rows from a DataFrame.
Args:
df (pandas.DataFrame): The DataFrame to extract rows from.
rows (list of int): The list of row numbers to extract, starting from 0.
Returns:
pandas.DataFrame: A new DataFrame containing only the specified rows.
"""
return df.iloc[rows]
```
使用示例:
```python
df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})
extract_rows(df, [0, 2])
```
输出:
```
col1 col2
0 1 4
2 3 6
```
阅读全文