经常被忽略的Python基本语法,常常,人,python,基础

发表时间:2020-10-22

python 编写常量板块

import sys

class _CONSTANT:
    class ConstantError(TypeError) : pass

    def __setattr__(self, key, value):
        if key in self.__dict__.keys():
            raise(self.ConstantError, "常量重新赋值错误!")
        self.__dict__[key] = value

sys.modules[__name__] = _CONSTANT()
#使用以下方式调用CONSTANT这个“常量”:
CONSTANT = _CONSTANT()
CONSTANT.TEST = 'test'
print(CONSTANT.TEST)
CONSTANT.TEST = 'test111'
print(CONSTANT.TEST)

使用更高精度(超过17位小数)

from decimal import *
print(getcontext())
getcontext().prec = 50
print(Decimal(1)/Decimal(9))
print(Decimal(1)/Decimal(19))
print(float(Decimal(1)/Decimal(19)))

四舍五入

##.5时取相邻的偶数
round(1.5) #2
round(2.5) #2 
rount(2.675) #3
##
##5左侧是奇数舍去,偶数向上取整
round(2.635, 2) #2.63
round(2.645, 2) #2.65
round(2.655, 2) #2.65
round(2.665, 2) #2.67
round(2.675, 2) #2.67
##
## ceil向上取整,floor向下取整
from math import ceil, floor
round(2.5) #2
ceil(2.5) #3
floor(2.5) #2
round(2.3) #2
ceil(2.3) #3
floor(2.3) #2

用complex创建复数

print(complex(1))			# 只有实部1
print(complex(1, 2))		# 实部为1,虚部为2
print(complex('1+2j'))		# 实部为1,虚部为2

迭代器

l = [1, 2, 3]
iterName=iter(l)
print(iterName)
print(next(iterName))
print(next(iterName))
print(next(iterName))
print(next(iterName))

数据清洗

import pandas as pd
#检查是否有重复数据
data=pd.read_csv('201711-2.csv', encoding='gbk')
for isDuplicate in data.duplicated():
    if isDuplicate==True:
        print(isDuplicate)
#检查空值
data.isnull()
#填充空值
data['IDNumber']=data['IDNumber'].fillna('123')
#去除左右两边的空格
data['CardNo']=data['CardNo'].map(str.strip)
#英文大小写转换
data['CardNo']=data['CardNo'].map(str.lower)
data['CardNo']=data['CardNo'].map(str.title)#首字母大写
data['CardNo']=data['CardNo'].map(str.upper)
#将日期型数据改成日期格式
data['CreateDateTime']=data['CreateDateTime'].fillna(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
data['CreateDateTime']=pd.to_datetime(data['CreateDateTime'])
#保存
data.to_csv('201711-2Clear.csv', encoding='gbk')

来源:《python 数据分析与可视化》

文章来源互联网,如有侵权,请联系管理员删除。邮箱:417803890@qq.com / QQ:417803890

微配音

Python Free

邮箱:417803890@qq.com
QQ:417803890

皖ICP备19001818号
© 2019 copyright www.pythonf.cn - All rights reserved

微信扫一扫关注公众号:

联系方式

Python Free