Pandas在Excel的几个sheet中读写数据的方法

Pandas在Excel的几个sheet中读写数据的方法

一)Pandas不覆盖现有sheet在Excel中写入数据

在平常把pandas写入Excel的时候,用到的是 df.to_excel('文件名.xlsx', sheet_name='sheet1'语句,示例如下:

A = np.array([[1,2,3],[4,5,6]])
df = pd.DataFrame(A)
df.to_excel('test_excel.xlsx',sheet_name='A')

只需要三行语句就可以搞定

但是,如果需要把两个DataFrame数据写入Excel文件中的不同sheet中,使用这种方法就有问题了:

A = np.array([[1,2,3],[4,5,6]])
B = np.array([[10, 20, 30], [40, 50, 60]])

df1 = pd.DataFrame(A)
df2 = pd.DataFrame(B)
df1.to_excel('test_excel.xlsx',sheet_name='AAA')
df2.to_excel('test_excel.xlsx',sheet_name='BBB')

执行以上程序之后,打开 “test_excel.xlsx” ,可以看到表格中只有名字为“BBB”的sheet保存下来了,而名字为“AAA”的sheet被覆盖掉了。

在这里插入图片描述

其实被覆盖的原因很好理解,程序在执行第二条写入语句的时候,默认以前的数据是没有用的,先清空这个Excel文件里的数据。

解决方法:

利用Pandas包中的ExcelWriter()方法增加一个公共句柄,在写入新的数据之时保留原来写入的数据,等到把所有的数据都写进去之后关闭这个句柄。示例如下:

writer = pd.ExcelWriter('test_excel.xlsx')
A = np.array([[1,2,3],[4,5,6]])
B = np.array([[10, 20, 30], [40, 50, 60]])

df1 = pd.DataFrame(A)
df2 = pd.DataFrame(B)
df1.to_excel(writer,sheet_name='AAA')
df2.to_excel(writer,sheet_name='BBB')
writer.close()

这样,两个sheet就都写入这个Excel中了:
在这里插入图片描述

最后,需要注意的是,很多博客给的示例是利用ExcelFile()方法新建句柄,可能以前的版本里可以,目前的版本使用这个函数程序执行类似操作是会报错的。具体原因以及两个函数用法的异同留待以后分析。

二)Pandas读取Excel的不同sheet中的数据

在读取有多个sheet的Excel时,如果不指定sheet名字,那么read_excel 函数默认读取第一个sheet中的数据。例如,我们使用一)中生成的“test_excel.xlsx”表格来进行测试

d1 = pd.read_excel('test_excel.xlsx')  #默认属性下读取
print("d1:\n",d1)
d2 = pd.read_excel('test_excel.xlsx',sheet_name = 'AAA')  #指定sheet名读取
print("dd1:\n",d2)
d3 = pd.read_excel('test_excel.xlsx',sheet_name = 'BBB')  #指定sheet名读取
print("d3:\n",d3)

显示结果如下:

d1:
    0  1  2
0  1  2  3
1  4  5  6

d2:
    0  1  2
0  1  2  3
1  4  5  6
d3:
  0   1   2
0  10  20  30
1  40  50  60

那么,如果我们想一条代码读取excel中的所有值时,可以将“sheet_name”属性指定为None,这样会得到一个字典变量,字典的key就是sheet名,value就是对应sheet里的数据。

例如以下代码:

    dd1 = pd.read_excel('test_excel.xlsx')
    print("dd1:\n",dd1)
    dd2 = pd.read_excel('test_excel.xlsx',None)
    print("dd2:\n",dd2)

效果如下:

dd1:
    0  1  2
0  1  2  3
1  4  5  6

dd2:
 OrderedDict([('AAA',    0  1  2
0  1  2  3
1  4  5  6), ('BBB',     0   1   2
0  10  20  30
1  40  50  60)])
发布了63 篇原创文章 · 获赞 189 · 访问量 27万+

猜你喜欢

转载自blog.csdn.net/u013044310/article/details/84947658