在`pandas`中,可以使用以下方法dataframe在指定位置添加行:
### 使用`concat`函数和索引切片
`concat`函数可以沿着指定轴将多个`DataFrame`连接在一起,可以先将原`DataFrame`拆分成两部分,再将需要添加的行与这两部分进行连接。示例如下:
```python
import pandas as pd
# 创建示例DataFrame
df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [6, 7, 8, 9, 10]})
# 要添加的行
new_row = pd.DataFrame({'A': [6], 'B': [11]})
# 指定插入位置
insert_index = 2
# 将df拆分为两部分
df_part1 = df.iloc[:insert_index]
df_part2 = df.iloc[insert_index:]
# 使用concat函数将三部分连接起来
result = pd.concat([df_part1, new_row, df_part2], ignore_index=True)
print(result)
```
其中ignore_index=True表示,忽略原来dataframe的索引,为生成的新的dataframe设置新的索引。
### 使用`loc`索引器
`loc`索引器可以按标签选择数据,`append`方法可以将一行或多行添加到`DataFrame`的末尾,结合起来可以在指定位置添加行。示例如下:
```python
import pandas as pd
# 创建示例DataFrame
df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [6, 7, 8, 9, 10]})
# 要添加的行
new_row = pd.DataFrame({'A': [6], 'B': [11]})
# 指定插入位置
insert_index = 2
# 使用loc
df = pd.concat([df.loc[:insert_index - 1], new_row, df.loc[insert_index:]]).reset_index(drop=True)
print(df)
```
其中,reset_index(drop=True)表示重置索引,丢弃原来的索引
### 使用`reindex`方法
`reindex`方法可以对`DataFrame`进行重新索引,可以通过重新索引在指定位置插入行。示例如下:
```python
import pandas as pd
# 创建示例DataFrame
df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [6, 7, 8, 9, 10]})
# 要添加的行
new_row = pd.DataFrame({'A': [6], 'B': [11]})
# 指定插入位置
insert_index = 2
# 生成新的索引列表
new_index = list(range(0, insert_index)) + ['new'] + list(range(insert_index, len(df)))
print(new_index)
# 使用reindex方法插入行
df = df.reindex(new_index).fillna('')
df.loc['new'] = new_row.values[0] # 给索引为‘new’的行赋值为6,11
df = df.reset_index(drop=True) # 重置索引将0, 1, 'new', 2, 3, 4重置为0, 1, 2, 3, 4, 5
print(df)
```