python常用计算函数总结
# pip 安装的时候,如果有些包已经存在,则用ignore忽略即可
# pip install moviepy --ignore-installed
import pandas as pd
import numpy as np
import random
from scipy import stats
import scipy as sp
import matplotlib.pyplot as mlp
import mhc_tools
#显示所有列
pd.set_option('display.max_columns', None)
pd.set_option('display.max_columns', None)
#显示所有行
pd.set_option('display.max_rows', None)
#设置value的显示长度为100,默认为50
# 常规格式化
'percent: {:.2%}'.format(42/50) #输出百分比
'percent: {:.2f}%'.format(42/50*100) #先转换成为百分位数
"%.2f%%" % (42/50)
# 求对数
x=np.e # log的默认底数是自然对数e
y=np.log(x)
# 反函数
x=np.e**y
# 求整、向上取整、向下取整、取余数、求商
import math
x=int(12/13) #四舍五入
x=math.ceil(12/13) #向上取整,1
x=math.floor(12/13) #向下取整,0
x=16%13 #取余数,3
x=15//13 #求商,1
x=divmod(16,13) # 求商和余数,(1, 3)
# 求平均值、众数、中位数、均方差、标准差
age=np.random.randint(1,10,10)
age_mean = np.mean(age) #均值
age_median=np.median(age) #中位数
age_mode=stats.mode(age)[0][0] #众数
age_4quantile=np.percentile(age, (25, 50, 75), interpolation='midpoint') #四分位数
age_var=np.var(age) # 方差
age_std=np.std(age,ddof=1) #标准差
# 统计某一列的元素频数
df = pd.DataFrame({'x':['a','a','b'], 'y':[2,2,6]})
x=df.x.value_counts() # 统计元素个数
df.x.nunique() # 统计不重复元素数
x=df.describe() # 统计性描述:最大、最小、方差、四分位数
# cut分组
number=np.random.random(10)
bins=[0,50,200,max(number)+1]
labels=['10','30','45']
pd.cut(number,bins) #按照指定序列分组
pd.cut(number,5) #均分
pd.qcut(number,5) #符合正太分布
# datframe 去重统计
df = pd.DataFrame({'x':['a','a','b'], 'y':[2,2,6]})
df.groupby('x').agg({'x':pd.Series.nunique})
# 取重复数据
data1=df.drop_duplicates(subset=None,keep='first',inplace=False)
data2=df.drop_duplicates(subset=None,keep=False,inplace=False)
data3=data1.append(data2).drop_duplicates(subset=None,keep=False,inplace=False)
df_duplicate=df.loc[df['x'].isin(data3['x'])]
df_duplicate=df.loc[df['x'].isin(df[df.duplicated()]['x'])]
# dataframe转字典
df = pd.DataFrame({'x':['a','a','b'], 'y':[4,2,6]})
df.T.to_dict(orient='list')
# list转字典
import string
num=string.ascii_letters+string.digits
list1=random.sample(num,10)
list2=np.random.random(5)
dict(zip(list1,list2))
方法一:
知识点:random.sample(sequence, k) 从指定序列中随机获取指定长度的片断
import random,string
num=string.ascii_letters+string.digits
print ( "".join(random.sample(num,10)) )
方法二:
知识点:random.choice(sequence) 从序列中获取一个随机元素
import random,string
passwd=""
num=string.ascii_letters+string.digits
for i in range(10):
passwd+=random.choice(num)
print (passwd)
方法三:
知识点:random.randint(a,b) 用于生成一个指定范围内的整数
import random,string
passwd = []
letters = string.ascii_letters + string.digits
length = len(letters)
for i in range(10):
letter = letters[random.randint(0,length - 1)]
passwd.append(letter)
print("".join(passwd))
方法四:列表、random.choice()、 random.randint()
import random
import string
passwd = []
for i in range(10):
if random.randint(0,1):
letter = random.choice(string.ascii_letters)
passwd.append(letter)
else:
letter = random.choice(string.digits)
passwd.append(letter)
print("".join(passwd))
方法五:
知识点:推导列表、random.choice()、 random.randint()
import random,string
推导列表1:
print ("".join([random.choice(string.ascii_letters) if random.randint(0,1) else random.choice(string.digits) for i in range(10)]))
推导列表2:
print ([random.choice(string.ascii_letters+string.digits) for i in range(10)])