pandas DataFrame 写入excel是列表 读取变字符串的解决办法

import pandas as pd

字典转DataFrame

d = {
    
    'one': [[1, 2], [3, 4], [5, 6]], 'two': [[7, 8], [9, 10], [11, 12]]}
df = pd.DataFrame(d)
df

在这里插入图片描述

查看DataFrame中的数据类型

for index, row in df.iterrows():
    print(type(row['one']))
<class 'list'>
<class 'list'>
<class 'list'>

写入eccel

df.to_excel(
    excel_writer=r"4.xlsx",  # 文件路径
    sheet_name='Sheet1',  # 子表的名字
    index=True,  # 是否写入index
    header=True,  # 是否写入列
    encoding="utf-8"  # 编码结构
)

读取excel

df1 = pd.read_excel(
    io=r"4.xlsx",  # 文件路径
    sheet_name='Sheet1',  # 子表名
    index_col=0,  # 用作索引的列
    header=0,  # 用列名的行
#     dtype=np.float64
)
df1

发现数据类型由列表变成了字符串,并修改数据结构

for index, row in df1.iterrows():
    print(type(row['one']))
    row['one'] = eval(row['one'])
<class 'str'>
<class 'str'>
<class 'str'>

修改成功

for index, row in df1.iterrows():
    print(type(row['one']))
<class 'list'>
<class 'list'>
<class 'list'>

猜你喜欢

转载自blog.csdn.net/weixin_44493841/article/details/121356185