pandas 函数 .append(df, ignore_index=True) 导致少索引这列怎么恢复这一列
时间: 2024-02-06 12:12:10 浏览: 37
如果使用 `.append(df, ignore_index=True)` 方法导致索引列丢失,可以使用以下方法恢复索引列:
1. 使用 `.reset_index()` 方法重新生成索引列。
```
df = df.append(new_df, ignore_index=True)
df = df.reset_index(drop=True)
```
2. 在新的 DataFrame 中手动添加索引列。
```
df = df.append(new_df, ignore_index=True)
df['index'] = range(len(df))
```
以上两种方法都可以恢复索引列,具体选择哪一种取决于具体的需求和情况。
相关问题
df2 = df2.append(df1, ignore_index=True)将df1作为行添加到df2中时,提示'DataFrame' object has no attribute 'append'
如果您在使用 'DataFrame' object 的时候提示 'DataFrame' object has no attribute 'append' 的话,有可能是您的 pandas 版本太低。这个方法在新版的 pandas 中已经被弃用了。您可以使用concat()函数来实现行添加操作,例如:df2 = pd.concat([df2, df1], ignore_index=True)。这个函数的第一个参数是要拼接的 DataFrame 列表,第二个参数 ignore_index=True 表示忽略原有索引并重新生成新的索引。
import pandas as pdimport ospath = 'path/to/folder'excel_files = os.listdir(path)df_list = []for file in excel_files: if file.endswith('.xlsx'): df = pd.read_excel(os.path.join(path, file)) df_list.append(df)merged_df = pd.concat(df_list, ignore_index=True)deduplicated_df = merged_df.drop_duplicates()deduplicated_df.to_excel('path/to/output/file.xlsx', index=False)
这段代码是用于读取一个文件夹下的所有 Excel 文件,将它们合并为一个 Pandas DataFrame,并且去除其中的重复行,最后将结果保存为一个新的 Excel 文件。
具体步骤如下:
1. 首先,导入 pandas 和 os 模块。
2. 设置变量 path 为待读取的文件夹的路径。
3. 使用 os.listdir(path) 函数列出 path 文件夹下的所有文件和文件夹,并将它们存储在 excel_files 列表中。
4. 创建一个空的 DataFrame 列表 df_list 用于存储每个 Excel 文件读取后得到的 DataFrame。
5. 遍历 excel_files 中的每个文件,如果文件名以 .xlsx 结尾,则读取该 Excel 文件,将其存储为 DataFrame,并将 DataFrame 添加到 df_list 列表中。
6. 使用 pd.concat() 函数将 df_list 中的所有 DataFrame 合并为一个 DataFrame,并将 ignore_index 参数设置为 True,以重置索引。
7. 对合并后的 DataFrame 进行去重,使用 drop_duplicates() 函数,该函数删除 DataFrame 中的重复行。
8. 最后,使用 to_excel() 函数将去重后的 DataFrame 保存为一个新的 Excel 文件,同时将 index 参数设置为 False,以避免将索引作为列写入 Excel 文件。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)