Python
Asher117
大家好,我是Asher,热衷于研究数据分析、数据挖掘以及网络爬虫等。大家有问题的话,欢迎加我微信,一起学习-分享-成长,MyWechat:liu2536036458
展开
-
【Python】Gensim安装好后使用报错
这里写自定义目录标题Gensim报错解决办法Gensim报错首次安装Gensim扩展包后,导入扩展包直接报错,如下import gensimRuntimeError: Compiled extensions are unavailable. If you've installed from a package, ask the package maintainer to include compiled extensions. If you're building Gensim from sour原创 2021-11-10 14:51:34 · 4173 阅读 · 9 评论 -
【Python】使用PdfFileMerger合并pdf时报错PdfReadError: Unexpected destination ‘/__WKANCHOR_2‘
在python中使用PyPDF2扩展包的PdfFileMerger函数合并pdf时,代码如下:merger = PdfFileMerger()input1 = open(r"2.pdf", "rb")input2 = open(r"3.pdf", "rb")merger.append(input1)merger.append(input2)# Write to an output PDF documentoutput = open(r"1.pdf", "wb")merger.write(ou原创 2021-01-12 16:02:51 · 2432 阅读 · 0 评论 -
【Python】使用pdfkit报错:OSError: wkhtmltopdf exited with non-zero code 1. error:
在工作自动化过程中,有时需要使用Python的pdfkit包将URL或者str等转换成pdf文件,今天使用如下代码在将str转换为pdf时,代码如下:options = {'page-size':'Letter','margin-top':'0.75in','margin-right':'0.75in','margin-bottom':'0.75in','margin-left':'0.75in','encoding':"UTF-8",'custom-header': [('Accept-Enco原创 2021-01-12 16:00:20 · 4221 阅读 · 1 评论 -
【Python】使用pdfkit将str或者URL转化为PDF时报错:OSError: No wkhtmltopdf executable found
在使用pdfkit.from_string或者pdfkit.from_file或者pdfkit.from_url将字符串、文件或者网页内容转化为pdf时,报错:OSError: No wkhtmltopdf executable found原因很明显,就是没找到可执行的wkhtmltopdf文件,也就是未找到wkhtmltopdf.exe文件。python的pdfkit扩展包使用时需要基于wkhtmltopdf.exe这个可执行文件才可运行,因此需要先安装wkhtmltopdf。对于windows原创 2021-01-12 15:58:00 · 3205 阅读 · 0 评论 -
【Python】操作word文档
#导入相关扩展包import docxfrom docx.enum.text import WD_ALIGN_PARAGRAPH#设置对齐格式from docx.shared import Pt#设置字体大小from docx.shared import Inches#设置缩进,图片大小等from docx.oxml.ns import qn#(1)写入word文件#首先,创建一个Document对象,即word文档doc = docx.Document()#添加一段文字p1 =原创 2020-12-21 23:32:35 · 573 阅读 · 0 评论 -
【Python】plt.savefig()保存图片不完整,x轴标签被截断
今天在用Python的plt.savefig()函数保存图片到本地时,发现保存下来的图片不完整,x轴标签被截断了。经过一番搜索,找到了解决方法:加上参数bbox_inches = 'tight'即可:plt.savefig(r"figure.png",bbox_inches = 'tight')...原创 2020-12-21 23:30:12 · 13427 阅读 · 3 评论 -
【Python】ParserError: Error tokenizing data. C error: Expected 1 fields in line 144, saw 4
Python使用pd.read_csv报错ParserError: Error tokenizing data. C error: Expected 1 fields in line 144, saw 4解决方法:pd.read_csv(path,sep='\t')原创 2020-12-21 23:27:35 · 2051 阅读 · 0 评论 -
【Python】获取excel所有的sheet名称
import pandas as pdpath = r"excel_file.xlsx"xlsx = pd.ExcelFile(path)xlsx.sheet_names #输出所有的sheet名称原创 2020-12-21 23:25:15 · 3138 阅读 · 3 评论 -
【Jupyter】快捷键
Enter : 转入编辑模式Esc : 退出编辑模式,进入命令模式Shift-Enter : 运行本单元,选中下个单元Ctrl-Enter : 运行本单元Alt-Enter : 运行本单元,在其下插入新单元1 : 设定 1 级标题2 : 设定 2 级标题3 : 设定 3 级标题4 : 设定 4 级标题5 : 设定 5 级标题6 : 设定 6 级标题Up : 选中上方单元Down : 选中下方单元A : 在上方插入新单元B : 在下方插入新单元X : 剪切选中的单元F:查找、替原创 2020-12-21 23:24:17 · 327 阅读 · 0 评论 -
【Python】补齐缺失日期
有DataFrame类型数据data,其中有index列为日期,另有value列,补充缺失日期列index代码如下:import pandas as pdimport datetime#创建DataFrame数据,包括index列和value列,其中index列为日期,但是格式为string格式data = pd.DataFrame(data={'index':['2020-10-09','2020-10-10','2020-10-17','2020-10-15'],'value':range(4原创 2020-12-21 20:03:31 · 6768 阅读 · 1 评论 -
【Python】移动、复制文件到另一个文件夹、删除文件(夹)
引入shutil模块import shutil复制或移动到目的文件夹下面shutil.copy('demo.txt','新的文件夹')file1.txt 移动到 新的文件夹 下面shutil.move('file1.txt','新的文件夹')复制或移动到目的文件夹下面之后,重命名shutil.copy('demo.txt','新的文件夹/new1.txt')shutil.move('file2.txt','新的文件夹/new2.txt')导入os模块import os删除 f原创 2020-10-14 20:45:50 · 25633 阅读 · 0 评论 -
【python3】写入excel文件(设置字体型号、边框样式、单元格对齐方式、合并单元格,列宽、行高等)
主要使用xlwt扩展包import xlwt创建workbook(Excel文件)workbook = xlwt.Workbook(encoding = 'utf-8')添加sheetsheet = workbook.add_sheet('sheetname')写入数据#格式:sheet.write(m,n,data),表示在第m行n列写入数据data#注意:m和n从0开始sheet.write(1,0,'第一行第0列')合并单元格,并写入数据#格式:#sheet.write_原创 2020-10-12 21:11:16 · 2242 阅读 · 0 评论 -
【Python】将xls格式转换为xlsx格式
Python批量将xls格式转换为xlsx格式,使用下面代码即可import win32com.client as win32fname = r'excelname.xls'excel = win32.gencache.EnsureDispatch('Excel.Application')wb = excel.Workbooks.Open(fname)wb.SaveAs(fname+"x", FileFormat = 51) #FileFormat = 51 is for .xlsx ext原创 2020-10-12 21:00:45 · 2983 阅读 · 1 评论 -
【pandas】df.str.contains包含多个值写法
直接上代码df['A'].str.contains('str1|str2')原创 2020-08-18 14:44:05 · 16503 阅读 · 7 评论 -
【pandas】ValueError: If using all scalar values, you must pass an index
使用pd.DataFrame函数创建df时,报错ValueError: If using all scalar values, you must pass an index:源代码:>>>pd.DataFrame(data = {'time':time,'length':length})>报错:>ValueError: If using all scalar values, you must pass an index修改方法一:>>>pd.原创 2020-08-18 14:23:54 · 1204 阅读 · 0 评论 -
【Jupyter】打开Jupyter notebook时,网页打不开
这个只需要在Jupyter Notebook文件中设置一下默认浏览器即可,步骤如下:1.打开anaconda prompt2.运行jupyter notebook --generate-config结果:3.复制上述文件路径,使用记事本打开4.找到#c.NotebookApp.browser = ‘’在下方加入import webbrowserwebbrowser.register("firefox",None,webbrowser.GenericBrowser(u"D:\\360Dow原创 2020-07-20 13:46:53 · 1889 阅读 · 1 评论 -
【Python】ValueError: The number of classes has to be greater than one; got 1 class
今天使用Python的sklearn模块训练模型时,报错ValueError: The number of classes has to be greater than one; got 1 class,如下:clf.fit(x,y)->ValueError: The number of classes has to be greater than one; got 1 class最后发现是样本原因,y变量只有一个类型,如下:y.value_counts()->-1 263原创 2020-07-19 14:24:22 · 9013 阅读 · 3 评论 -
【Python】安装docx模块后运行出行ModuleNotFoundError:No module named ‘docx‘
由于公司电脑不能联网,又需要用到docx扩展包,因此没办法直接用pip install在线安装,只能通过下载安装包,然后用u盘考进电脑之后在cmd下安装,刚开始我在官网上下载.gz文件之后,cmd下显示安装成功,然而运行导入模块时,还是报错:ModuleNotFoundError:No module named 'docx'因此,换了种方法,不去官网下载,去下面这个网址:https://www.lfd.uci.edu/~gohlke/pythonlibs/然后找到python_docx-0.8.6原创 2020-07-16 11:18:07 · 5030 阅读 · 0 评论 -
【Jupyter】更改默认文件存储路径
一般安装完Anaconda之后,打开Jupyter notebook都会发现默认是在C盘里面,而很多时候我们不想把代码放在C盘,而是放在其他自定义的路径里面,本文就是分享修改默认Jupyter notebook路径的方法,按照以下步骤即可:首先,打开Anaconda Prompt,运行命令jupyter notebook --generate-config,然后会输出jupyter_notebook_config.py文件所在路径,复制该路径使用记事本打开jupyter_notebook_config原创 2020-07-15 10:14:11 · 1175 阅读 · 1 评论 -
【Python】找出最大或最小的N个元素
在Python中,每次取最大或者最小元素比较容易,直接用max或者min函数就行,如下面代码:#Input:a = [1,3,4,3,7,3,9,3,1,2]print('max a is:', max(a))print('min a is:', min(a))#output:max a is: 9min a is: 1但是有时候我们需要输出最大或最小的N个数,这样的话如果只是用max和min的话就需要加一层循环,比较麻烦,这个时候可以考虑用nlargest和nsmallest函数了,如原创 2020-07-08 15:57:02 · 2529 阅读 · 0 评论 -
【Python】拆分任意长度的可迭代对象
Python作为现在主流的编程语言,有很多使用特性,比如今天要分享的可迭代对象的拆分。1.定长可迭代对象首先,对于固定长度或已知长度的可迭代对象(包括但不限于元组、列表、字符串等),可以通过复制给相同个数的变量即可:#inputtup = ('a', 2)x, y = tupprint('x=', x)print('y=', y)#outputx= ay= 22.任意长度可迭代对象使用"*表达式"即可,如下代码:#inputlistA = list('abcde')x, y原创 2020-07-06 11:16:43 · 449 阅读 · 0 评论 -
【python】dataframe和array相互转换
1.datafame转换成arrayMethod 1:df.as_matrix()Method 2:df.values2.array转换成dataframeMethod 1:pd.dataframe(array)原创 2020-06-30 12:12:52 · 39993 阅读 · 3 评论 -
【Python】logging.basicConfig函数
logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等。logging.basicConfig函数主要参数:logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d原创 2020-05-22 19:20:32 · 693 阅读 · 0 评论 -
df.apply函数有多个返回值
目标:将df.apply函数的多个返回值赋值到df的多个列中代码:先看返回值包含多列,如下:df1['RFRV'].apply(get_need)首先将这些多列放到df的一列中,再拆分为四列,如下:df1['text'] = df1['RFRV'].apply(get_need)df1[['complexity','comple_ci','num_ci','count']] = df1['text'].apply(pd.Series)...原创 2020-05-10 12:17:52 · 4658 阅读 · 0 评论 -
【Python】判断字符串中是否包含数字
通过正则表达式匹配,当字符串中包含数字时,返回True,否则返回Falsebool(re.search(r'\d', str))原创 2020-04-21 13:55:40 · 9962 阅读 · 3 评论 -
【Python】计算文本相似度
import jiebaimport numpy as npimport redef get_word_vector(s1,s2): """ :param s1: 句子1 :param s2: 句子2 :return: 返回句子的余弦相似度 """ # 分词 cut1 = jieba.cut(s1) cut2 = jieba....原创 2020-02-21 08:29:51 · 1562 阅读 · 0 评论 -
【Python】判断DataFrame里某个值在哪一列
通过如下代码输出某个值所在列:for col in X.columns: if(df[df[col].isin([某值])].shape[0]>0): print(col)原创 2020-02-07 08:28:42 · 5139 阅读 · 0 评论 -
【Python】对DataFrame进行分组排序
之前分享过在SQL里面进行分组排序的方法,这里分享一下Python对DataFrame进行分组排序的方法。假设我们有以下数据:IDData0110001200013000210002200分组排序方法:df['rank'] = df['Data'].groupby(df['ID']).rank()执行结果如下:IDD...原创 2019-12-31 17:44:52 · 4965 阅读 · 2 评论 -
【Python】报错:ConnectionError: ('Connection aborted.', BadStatusLine("''",))
报错:ConnectionError: (‘Connection aborted.’, BadStatusLine("’’",))原因:传入参数过多,拆分参数,再次传入即可原创 2019-12-01 14:38:01 · 6022 阅读 · 0 评论 -
【Python】读取CSV/Excel文件报错ParserError: NULL byte detected.解决方法
读取CSV文件报错如下:ParserError: NULL byte detected. This byte cannot be processed in Python’s native csv library at the moment, so please pass in engine=‘c’ instead解决方法,添加参数error_bad_lines=False即可pd.read_...原创 2019-12-01 12:36:13 · 6763 阅读 · 1 评论 -
【Python】列表操作大全
【列表】这篇文章总结了列表操作的函数大全。列表基础操作1.初始化构建List>>>aList = [2,9,5,6,12,0,4,7,5]>>>aList >[2, 9, 5, 6, 12, 0, 4, 7, 5]2.indexing:根据索引号取元素>>>aList[3]>63.concatenation:...原创 2019-04-15 14:17:01 · 454 阅读 · 0 评论 -
【Python】取字母的ASCII值
使用ord函数即可>>>ord('a')>97原创 2019-04-22 17:03:31 · 6898 阅读 · 0 评论 -
【Python】ParserError: Error tokenizing data. C error: Expected 13 fields in line 45, saw 23
#执行语句报错如下pd.read_csv(path)ParserError: Error tokenizing data. C error: Expected 13 fields in line 45, saw 23解决方法:pd.read_csv(path, error_bad_lines=False)原创 2019-04-17 15:55:41 · 3285 阅读 · 0 评论 -
【Python】输出指定文件夹下面的文件名
直接看例子:import osfile_dir = r"C:\Users\asher.liu\CodePython\CarData"for root, dirs, files in os.walk(file_dir): print(root) #当前目录路径 print(dirs) #当前路径下所有子目录 print(files) #当前路径下所有非目录子文件输...原创 2019-04-17 13:57:30 · 1381 阅读 · 0 评论 -
【Python】turtle库常用命令
常用绘图命令#向当前画笔方向移动d像素长度turtle.forward(d)#向当前画笔相反方向移动d像素长度turtle.backward(d)#顺时针移动degree度turtle.right(degree)#逆时针移动degree度turtle.left(degree)颜色设置#设置画笔颜色pencolor=color1turtle.pencolor(color...原创 2019-06-06 08:40:23 · 5279 阅读 · 0 评论 -
【Python算法与数据结构】一、数据结构与算法基础
1.数据结构:物理结构(展示) ->逻辑结构(内存表示)2.逻辑结构类型:集合:集合内数据无关系(除了同属一个集合之外)线性结构:一对一关系树:一对多关系图:多对多关系3.存储结构类型:线性存储链式存储索引存储哈希存储4.抽象数据类型(ADT):逻辑结构 + 抽象运算5.算法特性:有穷性:执行有穷个步骤确定性:无二义性可行性:输入:零个或多个输入输出:一...原创 2019-04-15 10:07:36 · 1444 阅读 · 0 评论 -
【Python】字符串和datetime相互转换
摘要时间序列(time series)数据是一种重要的结构化数据形式,应用于多个领域,包括金融学、经济学、生态学、神经科学、物理学等。在多个时间点观察或测量到的任何事物都可以形成一段时间序列。在进行时间序列问题分析时,通常需要将字符串和datetime类型相互转换,本文分享他们之间相互转换的集中常用方法(主要用到的库有datetime、pandas以及dateutil)。(一)datetime...原创 2019-06-06 12:34:26 · 14800 阅读 · 0 评论 -
【Python算法与数据结构】二、栈
1.栈的定义栈(Stack)是一种运算受限的线性表,只能在栈顶进行插入和删除操作。因此栈具有Last In First Out(FILO)特性。2.栈的操作a.Stack() 创建一个空的新栈。 它不需要参数,并返回一个空栈。b.push(item)将一个新项添加到栈的顶部。它需要 item 做参数并不返回任何内容。c.pop() 从栈中删除顶部项。它不需要参数并返回 item 。栈被...原创 2019-04-18 12:58:32 · 1080 阅读 · 0 评论 -
【Python】random模块主要函数
1.random.random用于生成一个0到1的随机符点数: 0 <= n < 1.02.random.uniform的函数原型为:random.uniform(a, b),用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。如果a > b,则生成的随机数n: a <= n <= b。如果 a <b, 则 b <= n <= ...原创 2019-05-19 10:59:38 · 1993 阅读 · 0 评论 -
【Anaconda】更改默认浏览器
1.打开anaconda prompt2.运行jupyter notebook --generate-config结果:3.复制上述文件路径,使用记事本打开4.找到#c.NotebookApp.browser = ‘’在下方加入import webbrowserwebbrowser.register("firefox",None,webbrowser.GenericBrowser...原创 2019-05-14 18:26:37 · 6730 阅读 · 0 评论