Python入門到實戰(五)conda使用、pandas操作Excel、資料可視化、繪制柱狀圖、操作Word、資料報表生成、pip install國內鏡像下載
- conda使用
- 常用操作
- 配置VS+Conda
- Python實作辦公自動化
- 操作Excel
- Pandas將資料寫入Excels
- Pandas讀取Excel資料并排序
- Pandas繪制資料
- 學習Pandas繪制柱狀圖
- 學習Pandas繪制疊加柱狀圖
- 操作Word
- 添加資料
- pip install xx 切換國內鏡像服務器下載,解決下載慢的問題
- ImportError: DLL load failed while importing etree: 找不到指定的模塊
- 案例 統計學生成績 資料報表的生成(Excel+Word)
conda使用
常用操作
查看環境中的所有包:conda list
安裝 XXX 包:conda install XXX
洗掉 XXX 包:conda remove XXX :
列出所有環境:conda env list
查看版本:conda–version
更新:conda update conda
創建環境:conda create -n<env_name> python=x.x
洗掉環境:conda remove -n<env_name> --all
洗掉指定環境:conda env remove -n XXX
激活環境:active <env_name>
退出環境:deactivate
配置VS+Conda
我配置三個環境變數,C:\Anaconda3;C:\Anaconda3\Scripts;C:\Anaconda3\Library\bin
在進入VSCode從Python.pythopath中改到Anaconda目錄下重啟VS后即可使用

Python實作辦公自動化
1 將Excel檔案讀入計算機
2 操作excel 資料可視化操作(pandas)
3 操作word (python-word)
操作Excel
Pandas將資料寫入Excels
Series與DataFrame:

In [1]: import pandas as pd
In [5]: df=pd.DataFrame({
...: 'id':[1,2,3],
...: 'name':['張','李四','王五'],
...: 'age':[19,20,21]
...: })
In [6]: df
Out[6]:
id name age
0 1 張 19
1 2 李四 20
2 3 王五 21
In [7]: df=df.set_index('id')
In [8]: df
Out[8]:
name age
id
1 張 19
2 李四 20
3 王五 21
In [11]: df.to_excel(r'C:\Users\ASUS\Desktop\MLCode\people.xlsx')
結果圖片:

Pandas讀取Excel資料并排序
下面一段代碼實作讀取上頭的Excel檔案并進行一個排序操作
In [17]: path='C:\\Users\\ASUS\\Desktop\\MLCode\\people.xlsx'
In [18]: people=pd.read_excel(path,sheet_name='Sheet1')
In [19]: people
Out[19]:
id name age
0 1 張 19
1 2 李四 20
2 3 王五 21
In [20]: people.sort_values(by='age',ascending=False,inplace=True)
#inplace表示就地,直接修改people,若為FALSE則會回傳一個物件,對people本身不會修改
In [21]: print(people)
id name age
2 3 王五 21
1 2 李四 20
0 1 張 19
Pandas繪制資料
學習Pandas繪制柱狀圖
想要通過Pandas可視化資料讀取student里的資料并通過可視化展示,代碼如下:
import pandas as pd
import matplotlib.pyplot as plt
students=pd.read_excel(r'C:\Users\ASUS\Desktop\MLCode\student.xlsx')
students.sort_values(by='Score',inplace=True,ascending=False)
plt.bar(students['Name'],students.Score,color='orange')
plt.title('Student score')#名稱是學生分數
plt.xlabel('Name')#橫坐標是name
plt.ylabel('score')#縱坐標是score
plt.xticks(students.Name,rotation='90')#學生名旋轉90讀
plt.tight_layout()
plt.show()

如圖所示,資料成功表示
如果需要顯示中文,則:
import pandas as pd
import matplotlib.pyplot as plt
students=pd.read_excel(r'C:\Users\ASUS\Desktop\MLCode\student.xlsx')
students.sort_values(by='Score',inplace=True,ascending=True)
# add chinese character support
from matplotlib.font_manager import FontProperties
font=FontProperties(fname=r"C:\Windows\Fonts\AdobeSongStd-Light.otf",size=16)
plt.bar(students['Name'],students.Score,color='orange')
plt.title('學生分數:',FontProperties=font)
plt.xlabel('名字',FontProperties=font)
plt.ylabel('分數',FontProperties=font)
plt.xticks(students.Name,rotation='90')
plt.tight_layout()
plt.show()
調庫,添加中文支持,用font物件接收,同時指定FontProperties為font即可、字體可從\Windows\Fonts\檔案夾目錄下尋找合適的字體,效果如下:

學習Pandas繪制疊加柱狀圖
表中:

Begin代表開學初期考試,middle代表期中考,final代表期末考,目標是求和并排序繪圖,代碼如下:
import pandas as pd
import matplotlib.pyplot as plt
stu=pd.read_excel(r'C:\Users\ASUS\Desktop\MLCode\threemon.xlsx')#讀檔案
stu['sum']=stu['Begin']+stu['Middle']+stu['Final']#求各時期考試和
stu.sort_values(by='sum',inplace=True)#排序
stu.plot.barh(x='Name',y=['Begin','Middle','Final'],stacked=True)#stack可實作疊加
plt.tight_layout()
plt.show()
結果:

操作Word
實作這個功能需要,pip install python-docx后使用Python-docx實作對Word的增刪改查
新建word檔案
from docx import Document
document=Document()
document.save('new.docx')
在創建了document物件后,其實就是一個實體了,你可以對它做任何操作,不過都是在記憶體中,當保存后,它將寫入磁盤
添加資料
document.add_paragraph(‘這是一個段落’)
document.add_heading(‘這是一個標題’,level=1)
document.add_page_break() #分頁符
table=document.add_table(rows=6,cols=6)
document.add_picture(‘xx.jpg’,width=Inches(1.25))
pip install xx 切換國內鏡像服務器下載,解決下載慢的問題
pip install python-docx總是安裝失敗嗎?就像下面這樣,或者速度太慢
(base) C:\Users\ASUS> pip install python-docx
Collecting python-docx
Downloading python-docx-0.8.10.tar.gz (5.5 MB)
|███████▌ | 1.3 MB 1.2 kB/s eta 1:00:46
下了5分鐘,就下載了這么一點,讓人絕望,
因為服務器在境外,默認下載源也都是在國外,這個時候就可以通過國內鏡像服務器下載,
pip國內的一些鏡像還有:
阿里云 http://mirrors.aliyun.com/pypi/simple/
中國科技大學 https://pypi.mirrors.ustc.edu.cn/simple/
豆瓣(douban) http://pypi.douban.com/simple/
清華大學 https://pypi.tuna.tsinghua.edu.cn/simple/
中國科學技術大學 http://pypi.mirrors.ustc.edu.cn/simple/
修改方法就是在打pip install XX后加上-i引數,指定pip源,如:pip install python-docx -i https://mirrors.bfsu.edu.cn/pypi/web/simple/
具體代碼如下
(base) C:\Users\ASUS> pip install python-docx -i https://mirrors.bfsu.edu.cn/pypi/web/simple/
Looking in indexes: https://mirrors.bfsu.edu.cn/pypi/web/simple/
Collecting python-docx
Downloading https://mirrors.bfsu.edu.cn/pypi/web/packages/e4/83/c66a1934ed5ed8ab1dbb9931f1779079f8bca0f6bbc5793c06c4b5e7d671/python-docx-0.8.10.tar.gz (5.5 MB)
|████████████████████████████████| 5.5 MB 3.3 MB/s
Requirement already satisfied: lxml>=2.3.2 in c:\software\anaconda\lib\site-packages (from python-docx) (4.6.1)
Building wheels for collected packages: python-docx
Building wheel for python-docx (setup.py) ... done
Created wheel for python-docx: filename=python_docx-0.8.10-py3-none-any.whl size=184495 sha256=63b082dbe118cb159bfba8e59a24cb64c1c7e8c4ceebc7477b2d6d1418d94ffb
Stored in directory: c:\users\asus\appdata\local\pip\cache\wheels\35\ba\36\4560ae617c53624d0f4026667ece078b5441eb6e49ef3ed0f0
Successfully built python-docx
Installing collected packages: python-docx
Successfully installed python-docx-0.8.10
ImportError: DLL load failed while importing etree: 找不到指定的模塊
其實我是要用Document但是卻提示我
from lxml import etree
ImportError: DLL load failed while importing etree: 找不到指定的程式
這個時候,先卸載,
PS C:\Users\ASUS\Desktop\MLCode> pip uninstall lxml
Found existing installation: lxml 4.6.1
Uninstalling lxml-4.6.1:
Would remove:
c:\software\anaconda\lib\site-packages\lxml-4.6.1.dist-info\*
c:\software\anaconda\lib\site-packages\lxml\*
Proceed (y/n)? y
Successfully uninstalled lxml-4.6.1
卸載完成后,在安裝,用中科大鏡像安裝
PS C:\Users\ASUS\Desktop\MLCode> pip install lxml -i https://mirrors.bfsu.edu.cn/pypi/web/simple/
Looking in indexes: https://mirrors.bfsu.edu.cn/pypi/web/simple/
Collecting lxml
Downloading https://mirrors.bfsu.edu.cn/pypi/web/packages/e7/bc/9e7f38333767146191afbb17simple/6ffd2c1d553589a11b7e499f12aacc6cf5cd/lxml-4.6.3-cp38-cp38-win_amd64.whl (3.5 MB)
|████████████████████████████████| 3.5 MB 3.3 MB/s
Installing collected packages: lxml 6ffd2c1d553589a11b7e499f12aacc6cf5cd/lxml-4.6.3-cp38-cp38-win_amd64.whl (3.5 MB)
Successfully installed lxml-4.6.3
這樣就成功了
希望能有所幫助
案例 統計學生成績 資料報表的生成(Excel+Word)
大致需求:
統計學生的分數,做從高到低排序,在匯出的word中有成績分析報告title、第一名學生成績和總共多少名考生參與了考試、
表格資料如下:

代碼:
from docx import Document
import pandas as pd
import matplotlib.pyplot as plt
imgname='chart.jpg'
stu=pd.read_excel(r'C:\Users\ASUS\Desktop\MLCode\student.xlsx')
stu.sort_values(by='Score',inplace=True,ascending=False)
plt.bar(stu.Name,stu.Score,color='orange')
plt.title('Score Chart')
plt.xlabel('Name:')
plt.ylabel('Score:')
plt.tight_layout()
plt.savefig(imgname)
docu=Document()
#標題
p=docu.add_heading('班里學生成績情況:',level=0)
f_stu=stu.iloc[0,:]['Name']#絕對位置去獲取
f_score=stu.iloc[0,:]['Score']#分數
p=docu.add_paragraph('班里的第一名是:')
p.add_run(f'{str(f_stu)}分數為:{str(f_score)}').bold=True
#班里情況
p1=docu.add_paragraph(f'有{len(stu.Name)}名學生考試了,總體情況如下:')
table=docu.add_table(rows=len(stu.Name)+1,cols=2)
table.cell(0,0).text='學生姓名:'
table.cell(0,1).text='學生分數:'
for i,(index,row) in enumerate(stu.iterrows()):
table.cell(i+1,0).text=str(row['Name'])
table.cell(i+1,1).text=str(row['Score'])
docu.add_picture(imgname)
docu.save('studentsReport.docx')
print('finish')
運行結果
c:\Users\ASUS\Desktop\MLCode\report.py'
finish

在目錄下都有新建檔案:

以上為自動化辦公的入門操作學習
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/281266.html
標籤:python
