![](https://img-blog.csdnimg.cn/20201014180756928.png?x-oss-process=image/resize,m_fixed,h_64,w_64)
python
文章平均质量分 92
NoOne-csdn
永远年轻,永远热泪盈眶
展开
-
pyspark group之后展开列表,计算列表个数
背景+-----------+-----------+|question_id|user_answer|+-----------+-----------+| 30530| 122306,|| 30548| 122378,|| 30451| 121990,|| 30530| 122304,|| 30548| 122378,|| 30451| 121990,|| 30530| 12原创 2020-06-03 15:12:42 · 1133 阅读 · 0 评论 -
pandas np.nan 替换成None
背景pandas处理合并数据时,空值有时候会被复制为np.nannp.nan默认为float类型,下一步处理有时候会相对麻烦需要把np.nan替换为None尝试df.replace(np.nan, None, inplace=True)不起作用solution df=df.where(df.notnull(), None)完美解决...原创 2020-05-27 11:57:55 · 6065 阅读 · 5 评论 -
pandas 分组,显示去重后列表元素和个数显示
uniquenuniqueaggs={'day_time':['nunique','unique']} gp=df.groupby(['user_id','subject_id']).agg(aggs)print(gp) day_time nunique原创 2020-05-11 15:22:01 · 1037 阅读 · 0 评论 -
python必知必会(持续更新)
最近在刷leetcode发现python好多小知识点是一知半解,不能熟练使用。特做此笔记。list.sort(cmp=None, key=None, reverse=False)解决问题:列表的元素的部分值排序dem题目应用: 重新排列日志文件背景:非全部字符排序a,b=log.split(" ", 1)Python split() 通过指定分隔符对字符串进行切片,如果...原创 2020-04-14 16:04:05 · 318 阅读 · 0 评论 -
python os 文件操作
import os'''1. os.getcwd()不需要传参,返回的是运行脚本所在的目录2. os.listdir(path):列举目录下所有的文件。返回的是列表类型'''d=os.getcwd()l=os.listdir(os.getcwd())print(d)print(l)'''2.os.path.abspath(path)返回path的绝对路径'''d...原创 2018-12-28 14:29:43 · 159 阅读 · 0 评论 -
ValueError: cannot switch from manual field specification to automatic field numbering
附源码:class SingletonObject(object): class __SingletonObject(): def __init__(self): print ('init') self.val=None def __str__(self): # print (...原创 2019-01-22 20:56:36 · 2184 阅读 · 0 评论 -
python 遍历文件夹下面所有文件
import ospath = '/Users/cyy/workspace/offcn/PMrequirements/re2019/0129专项-学段去重csv'path1 = '/Users/cyy/workspace/offcn/PMrequirements/re2019'def get_files(filepath): filess = [] files = o...原创 2019-02-21 14:59:40 · 558 阅读 · 0 评论 -
python os模块详解
os 模块,操作系统的接口返回当前工作目录 os.getcwd()#获得当前工作目录os.getcwd()'/Users/cyy/workspace/mypyspark'返回绝对路径 os.path.abspath(path)#返回绝对路径os.path.abspath(os.getcwd())'/Users/cyy/workspace/mypyspark'返回文...原创 2019-02-22 17:16:53 · 230 阅读 · 0 评论 -
pandas 合并相同ID的字符串
背景需求:题目查重,需合并选项。现已经获得目标题目ID以及选项,目标:相同question_id,合并选项思路:data=df.groupby(by='question_id')['choice'].sum()print(data)报错:原因: choice中有空致存在,最后更改如下:df=pd.read_csv('choices.csv')df=d...原创 2019-02-19 15:07:51 · 2118 阅读 · 2 评论 -
时间字符串处理arrow
import arrowimport timefrom datetime import datetime#获得当前时间戳tp=arrow.now().timestamptp=time.time()#将2019-02-14 08:00:00转换为时间戳tp=arrow.get('2019-02-14 08:00:00',tzinfo='local').timestampti...原创 2019-02-14 10:49:53 · 711 阅读 · 1 评论 -
python str.split str.splitlines 字符串分割返回列表
'''Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串'''str='"Line1-abcdef \nLine2-abc \nLine4-abcd"'print(str.split())print(str.split(' ',0))print(str.split(' ',1))print(str.split...原创 2019-02-20 09:27:11 · 1643 阅读 · 1 评论 -
python sys.modules
Python中所有加载到内存的模块都放在sys.modules。sys.modules是一个全局字典,字典sys.modules对于加载模块起到了缓冲的作用,当import一个模块时首先会在这个列表中查找是否已经加载了此模块,如果加载了则只是将模块的名字加入到正在调用import的模块的Local名字空间中。当第二次再导入该模块时,python会直接到字典中查找,从而加快了程序运行的速度。件,模块...原创 2019-01-24 10:34:30 · 3413 阅读 · 0 评论 -
python __name__
1.__name__就是一个变量2.如果模块是被导入,__name__的值为模块名字3.如果模块是被直接执行,__name__的值为‘__main__’例如:test1.py:print(__name__)执行test1.pytest2.py:from test1 import *执行test2.py ...原创 2019-01-24 10:23:30 · 99 阅读 · 1 评论 -
python locals() globals()
import osfrom os import pathprint(locals())print(globals())'''locals() 以字典的形式返回当前位置的全部局部变量globals() 以字典的形式返回全局变量'''def add(arg): z=1 print(locals()) print(globals()) return...原创 2018-12-28 14:42:08 · 473 阅读 · 0 评论 -
python wordcloud 参数
转自https://www.cnblogs.com/delav/articles/7837975.html font_path : string #字体路径,需要展现什么字体就把该字体路径+后缀名写上,如:font_path = '黑体.ttf'width : int (default=400) #输出的画布宽度,默认为400像素height : int (default=200...转载 2018-12-28 16:20:59 · 1245 阅读 · 0 评论 -
python deque 双端队列模块
参考:官网文档'''Deque 模块是python 标准库collections中的一项,它提供了两端都可以操作的队列,意味着,你可以在序列前后执行添加或者删除;'''from collections import dequed = deque('ghi') # make a new deque with three itemsfor elem ...转载 2018-12-23 14:43:07 · 153 阅读 · 0 评论 -
python loguru
参考https://github.com/Delgan/logurupip install loguruloguru 是一个友好的python 日志库 基本用法:import sysfrom loguru import loggerlogger.debug("That's it, beautiful and simple logging!")添加日志文件...翻译 2018-12-18 16:08:25 · 3524 阅读 · 0 评论 -
python 下划线
转载自https://zhuanlan.zhihu.com/p/36173202本文介绍了Python中单下划线和双下划线("dunder")的各种含义和命名约定,名称修饰(name mangling)的工作原理,以及它如何影响你自己的Python类。单下划线和双下划线在Python变量和方法名称中都各有其含义。有一些含义仅仅是依照约定,被视作是对程序员的提示 - 而有一些含义是由Pyth...转载 2018-12-24 17:42:09 · 103 阅读 · 1 评论 -
python lambda if elif else
sourcedf['地区']=sourcedf['exam_district'].apply(lambda x:"全国" if x==1 else ("北京" if x==3 else("上海" if x==24 else "其他地区")) )lamada(表达式 if 条件 else (表达式 if 条件 else(…………)))...原创 2019-01-10 14:36:32 · 33587 阅读 · 4 评论 -
python schedule 轻量定时任务
import scheduleimport time''' schedule 一个轻量的定时任务库,可以完成特定时期的定时任务eg:'''def run(): print("i am running")schedule.every().days.at("2:00").do(run) # 每天凌晨两点运行程序schedule.every().minute.do(...原创 2019-01-10 16:03:21 · 1762 阅读 · 0 评论 -
apandas 分组并字符串拼接
源:目标:方法:choiceres=choicedf.pivot_table(values='choice',index='question_id',aggfunc=lambda x:x.str.cat())原创 2018-12-26 11:55:09 · 1750 阅读 · 3 评论 -
python __slot__ 限制类的属性
作用:限定一个类创建的实例只能有固定的属性(实例变量),不允许对象添加列表以外的属性 防止用户因错写属性的名称而发生程序错误说明:含有__slots__属性的类所创建的实例没有__dict__属性,即此实例不用字典来存储对象的属性实例:class Point(): __slots__ = ("x", "y") def __init__(self, x, ...原创 2019-01-24 10:11:44 · 394 阅读 · 0 评论 -
python shuffle 函数
import random'''huffle(lst) 方法将序列的所有元素随机排序。lst -- 可以是一个序列或者元组该函数没有返回值'''li=list('abcdef')a=random.shuffle(li)print(li)b=random.shuffle(li)print(li)print(a)print(b)...原创 2019-02-26 10:24:40 · 602 阅读 · 0 评论 -
pandas 创建DataFrame
class pandas_tool(): def __init__(self): self.dutikuengine = create_engine( "mysql+pymysql://*******m:3306/tiku?charset=utf8") pass#字典创建 def get_by_dict(self): ...原创 2019-02-20 20:35:45 · 133 阅读 · 0 评论 -
代码注释TODO、FIXME、XXX
#TODO:有功能代码带编写#FIXME: 有代码待改进或者不理想#XXX: 实现方法待改进转载 2019-06-05 20:51:56 · 935 阅读 · 0 评论 -
python 迭代器和生成器
概念迭代:按照一定的顺序诸葛访问容器中的每一个元素的过程迭代器协议对象需要提供next方法,它要么返回迭代中的下一项,要么就引起一个StopIteration异常,以终止迭代 :iterable(可迭代对象):可直接作用于for循环的对象成为可迭代对象。具体的实现是对象只要定义了iter方法,或者定义了支持下标索引的getitem方法,那么这个对象就说可迭代对象。from collect...原创 2019-06-06 16:27:13 · 74 阅读 · 0 评论 -
python函数装饰器、类装饰器和带参数的装饰器——装饰器模式
装饰器模式:动态地给对象添加一些额外的职责,就增加功能来说,装饰模式比生产子类更加灵活Component 是定义一个对象接口,可以给这些对象动态地添加职责。concreteComponent是定义一个具体对象,也可以给这个对象添加一些职责。decorator,装饰抽象类,继承l component,从外类来扩展component类的功能,但对于component来说,是无需知道decorat...原创 2019-06-11 20:30:32 · 665 阅读 · 0 评论 -
日常笔记之 txt文件转csv文件
0719 txt文件转csvmethod1 a=list(csv.reader(open('a.txt', 'r'), delimiter='\t')) df=pd.DataFrame(a)df.to_csv("res.csv")method2 with open('a.txt', 'r') as infile, open('t.csv', 'w') as outfile: ...原创 2019-07-19 10:42:20 · 349 阅读 · 0 评论 -
pyspark.sql module 之SparkSession(待续)
Mocule ContextSpark SQL 和DF重要的类类名说明SparkSessionDF以及SQL的入口DataFrame分布式数据集ColumnDF的一列RowDF的一行GroupedDatadf.groupBy()的一些操作方法DataFrameNafunction处理缺失数据的方法DataFrameStatFu...原创 2019-08-15 16:28:36 · 1269 阅读 · 0 评论 -
pyspark.sql之DataFrame
DataFrameagg(*exprs) 同df.groupBy.agg()df.agg({"age":"sum"}).show()±-------+|sum(age)|±-------+| 13|±-------+df.agg({"age":"min"}).show()±-------+|min(age)|±-------+| 1|±-...原创 2019-08-16 09:39:54 · 482 阅读 · 0 评论 -
spark persist cache()以及StorageLevel
cache() 以及persist()都是用于将一个RDD进行缓存的,这样在之后使用的过程中就不需要重新计算了,可以大大节省程序运行时间cache()区别cache()的缓存机制为MEMORY_AND_DISK。即RDD的数据直接以Java对象的形式存储于JVM的内存中,如果内存空间不中,某些分区的数据会被存储至磁盘,使用的时候从磁盘读取。persist()persist的默认缓存机制为s...原创 2019-08-16 10:21:37 · 2133 阅读 · 0 评论 -
unsupported format character '}' (0x7d) at index 83
背景:python 更新mysql数据库报错:插入语句:update t_question_re_math set error_info='',img_latex='\frac { 1.1 } { 1 + 8.2 \% }' where id=1048报错:unsupported format character '}' (0x7d) at index 83原因:sql 语句中包...原创 2019-05-30 09:42:56 · 2489 阅读 · 0 评论 -
python glob 指定路径查找匹配文件
递归指定目录,查询匹配文件glob.glob() 返回列表glob.ilob()返回迭代器resfile=glob.glob(r'/Users/xxxx/**/*.jpg',recursive=True)说明:递归查询‘/Users/xxxx/’下的所有文件参考https://docs.python.org/3/library/glob.html...翻译 2019-05-22 11:16:17 · 1648 阅读 · 0 评论 -
mac autopep8
命令行 autopep8 --in-place --aggressive --aggressive <filename>pycharmTools-External Tools2.运行时提示permission denied原因:autopep8.py这个文件没有执行权限解决办法:chmod 755 autopep8.py...原创 2019-05-06 14:56:12 · 680 阅读 · 0 评论 -
python os设置环境变量
一、设置系统环境变量1、os.environ[‘环境变量名称’]=‘环境变量值’ #其中key和value均为string类型2、os.putenv(‘环境变量名称’, ‘环境变量值’)二、获取系统环境变量1、os.environ[‘环境变量名称’]2、os.getenv(‘环境变量名称’)...翻译 2019-03-14 10:56:32 · 17347 阅读 · 0 评论 -
Fatal Python error: Py_Initialize: unable to load the file system codec
打开terminal报错Could not find platform independent libraries <prefix>Could not find platform dependent libraries <exec_prefix>Consider setting $PYTHONHOME to <prefix>[:<exec_prefi...原创 2019-03-15 15:45:51 · 3937 阅读 · 1 评论 -
inappropriate ioctl for device(待解决)
背景:ju py te r 运行线上环境,报错 [Errno 25] Inappropriate ioctl for device原创 2019-03-31 12:57:36 · 25111 阅读 · 0 评论 -
python中collections.namedtuple
collections是Python内建的一个集合模块,提供了许多有用的集合类。collections.namedtuple是一个工厂方法,它可以动态的创建一个继承tuple的子类。跟tuple相比,返回的子类可以使用名称来访问元素。namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。这样一来...原创 2019-04-10 11:00:12 · 1318 阅读 · 1 评论 -
python小知识必知必会
1 Python ord() 函数ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。...原创 2019-04-10 11:41:05 · 122 阅读 · 0 评论 -
python 模块bisect
bisect是 python 的内置模块,主要用来排序方法:bisect.bisect(a, x, lo=0, hi=None)bisect.bisect_left(a, x, lo=0, hi=None)bisect.bisect_right(a, x, lo=0, hi=None)bisect.insort(a, x, lo=0, hi=None)bisect.insort_le...原创 2019-04-10 14:14:05 · 17371 阅读 · 1 评论