Q-Logo 我的学习笔记分享

Entries for tag "python"

Python 命令行运行py文件报错ModuleNotFoundError: No module named 'XXX'

一是设置 PYTHONPATH 环境变量,将自己的项目目录加入到其中,如果没有就创建一个。不同操作系统设置方式会有区别,可针对自己用的操作系统自行搜索怎样设置环境变量。

二是在报错的py文件中,通过sys、os等模块将需要添加的路径追加到sys.path 中,例如,用下面的方式将报错文件的父目录追加到sys.path 中

import sys
import os
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)

这样就可以让Python 找到需要的模块了。

pip 安装wheel 报错xxx.whl is not a supported wheel on this platform.

pip 安装wheel 格式的包时,如果版本不对会报“xxxx.whl is not a supported wheel on this platform”的错误,以本地python 版本为python3.7,安装pycairo为例,

pip install /path/to/pycairo-1.19.1-cp39-cp39-win32.whl

pycairo-1.19.1-cp39-cp39-win32.whl is not a supported wheel on this platform.

文件名中一般会包含类似cp27 或 cp39 等字符串,表明.whl文件所支持的python 版本,需要选择与自己的python 版本对应的wheel 文件。像上面这种情况,只需下载pycairo-1.19.1-cp37-cp37m-win_amd64.whl 这个版本的wheel 文件,再安装就可以了。

另外,还可以通过如下命令查看本地Python 支持的wheel 文件

>>> import pip._internal

>>> pip._internal.pep425tags.get_supported()

用Python 将图片中的白色背景改为透明

原始白色背景图片是这样的

爱心.png

希望处理后,爱心外面和里面的白色背景都变成透明的,像这样

爱心透明背景.png

代码

import PIL.Image as Image

img_file = 'C:\\Pictures\\爱心.png'

output_file = 'C:\\Pictures\\爱心透明背景.png'

img = Image.open(img_file)

img = img.convert('RGBA')

W, H = img.size

white_pixel = (255, 255, 255, 255)

for h in range(H):

for w in range(W):

if img.getpixel((w,h)) == white_pixel:

img.putpixel((w,h),(255,255,255,0))

img.save(output_file)

Pandas DataFrame的round函数详解及小坑

df.round(decimals=0, *args, **kwargs)

输入参数

decimals : int, dict, Series,每一列舍入到的小数位数。如果是整数,每一列都被舍入到这个位数;如果是字典或序列,各列舍入到指定的精度。列的名字应该作为decimals 字典的键,或者decimals 序列的index。未在decimals 中指定精度的列将保留原样。如果decimals 中有不是列名的键或index,会被忽略。

返回:

DataFrame: 舍入到指定精度的DataFrame。

decimals=0时,返回的是浮点数而非整数。

round 并非四舍五入,对浮点数执行round 须谨慎。