Pandas读取表格存入列表
时间: 2023-06-09 13:08:13 浏览: 118
可以使用 Pandas 的 read_excel() 或 read_csv() 方法来读取表格文件,并将表格数据存入一个列表中。例如,使用 read_excel() 方法读取 Excel 文件:
```
import pandas as pd
# 读取 Excel 文件
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')
# 将表格数据存入列表
data = df.values.tolist()
```
同样,使用 read_csv() 方法读取 CSV 文件:
```
import pandas as pd
# 读取 CSV 文件
df = pd.read_csv('data.csv')
# 将表格数据存入列表
data = df.values.tolist()
```
注意,使用 read_excel() 方法需要安装 openpyxl 和 xlrd 库,而使用 read_csv() 方法则不需要。
相关问题
python pandas 将读取的表格的数据存入当前表格的新的工作🙅
在 Pandas 中,可以使用 `to_excel()` 方法将 DataFrame 存储在 Excel 文件中。如果要将数据存储在当前打开的 Excel 文件中的新工作表中,可以使用 `openpyxl` 库来实现。
以下是将 Pandas 中的 DataFrame 存储在 Excel 文件中新工作表的示例代码:
``` python
import pandas as pd
from openpyxl import load_workbook
# 读取 Excel 文件中的数据
df = pd.read_excel('data.xlsx')
# 打开 Excel 文件
book = load_workbook('data.xlsx')
# 创建新工作表,并将数据写入新工作表中
writer = pd.ExcelWriter('data.xlsx', engine='openpyxl')
writer.book = book
df.to_excel(writer, index=False, sheet_name='NewSheet')
# 保存 Excel 文件
writer.save()
```
其中,`load_workbook()` 方法用于打开 Excel 文件,`writer.book` 属性用于设置 Pandas 中的 ExcelWriter 对象所要写入的 Excel 文件对象。`to_excel()` 方法用于将 DataFrame 写入新工作表中,`index=False` 参数用于指定不将 DataFrame 中的行索引写入 Excel 文件中。
执行上面的代码后,DataFrame 中的数据将被写入 Excel 文件的新工作表中。
python pandas将表格数据分别存入新表格sheet1和sheet2
假设你已经用 Pandas 读取了表格数据并存储在名为 `df` 的 DataFrame 中,可以按照以下步骤将数据分别存入新表格的 Sheet1 和 Sheet2 中:
```python
import pandas as pd
# 读取原始表格数据
df = pd.read_excel('原始表格.xlsx')
# 将数据按照条件分成两个 DataFrame
condition = df['条件列'] == '条件值'
df_sheet1 = df[condition]
df_sheet2 = df[~condition]
# 创建新表格并将两个 DataFrame 存储在不同的 Sheet 中
writer = pd.ExcelWriter('新表格.xlsx', engine='xlsxwriter')
df_sheet1.to_excel(writer, sheet_name='Sheet1')
df_sheet2.to_excel(writer, sheet_name='Sheet2')
writer.save()
```
其中,`df_sheet1` 和 `df_sheet2` 分别是按照条件分割后的两个 DataFrame,`writer` 是用于创建新表格的 ExcelWriter 对象,`to_excel()` 方法用于将 DataFrame 存储在指定的 Sheet 中,`writer.save()` 方法用于保存新表格。
阅读全文
相关推荐
















