python笔记

来源:互联网 发布:阿里云企业邮箱设置 编辑:程序博客网 时间:2024/05/20 16:41

dict转df:
df_dict = pd.DataFrame(dict_.values(),index = dict_.keys())
python调用Linux命令并返回输出结果:
result=os.popen(cmd).read()
解决"UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128)"
reload(sys)
sys.setdefaultencoding('utf-8')reload(sys)
sys.setdefaultencoding('utf-8')
读gz: gzip.open(file_route,"r") as f:
读zip: z = zipfile.ZipFile(file_route, "r")
多分隔符:
import re
u_list = re.split(" |\n|\t",str)
多个列表的交集求法:
        list_data = [[1,2,],[1,3],[1,4]]
        intersection_list = list(set(list_data[0]).intersection(*list_data[1:]))

spyder 注释颜色:#c8977a
打印三角矩阵 http://blog.csdn.net/wangqing84411433/article/details/53150207
    for j in range(n-1):
        for k in range(j+1):
if j == n-1:contine #(不包括反对角线)
                print a[k][j-k]
python将字符串转字典
a = '{'a':1,'b':2}' #str类型
b = eval(a) #dict类型
取两个list里面的交集,并集,差集
  1. print list(set(a).intersection(set(b))) #交集
  2. print list(set(a).union(set(b))) #并集
  3. print list(set(b).difference(set(a))) #差集
统计list里各元素的个数
from collections import Counter 
values_counts = Counter(list) #返回一个字典,key是list里的元素,value是个数
top_2 = values_counts.most_common(2)  
print(top_2)
pd.read_table()
遇到 Expected X fields in line n, saw X,可以跳过此条数据 pd.read_table(skiprows = n)
python 1.正则表达式
(1) . 匹配当前位置除换行外任意一个字符
(2) * 匹配前一个字符0次或无限次
(3) ? 匹配前一个字符0次或1次
(4) .*? 匹配所有字符
(5) (.*?)所需要找的字符(前后要有指示性的字符包裹 如:s.*?a(.*?)b.*?sf )

编码格式:gb18030 gb2312
python DataFrame
不需要行列,header = None
DataFrame去重:data = data.drop_duplicates()
data['3']列名字为3,data[3]第三列(从0开始数)
DataFrame索引最后一个值:df.index.argmax()
java强转 (float) latitude
python强转 int('20') 20
round(num,3)取精度,小数点保留3位
要用 in 判断一个元素是否存在一个列中data[0]中,先转为list, a in list(data[0])
单独取出一行,合并,
concat_1 = DataFrame([data.irow(index)])
concat_frame = pd.concat([concat_frame,concat_1])
如果page = requests.get(url) page.text乱码了,可以page.encoding = 'gbk'或者其他的编码。
安装外部包 python setup.py install
httpFox 火狐浏览器插件获取postdata,headers等信息

把某列作为索引:
data = data.set_index([0])
列排序:
data.sort_values(['col1','col2',ascending = False]
列计数(groupby(['col1']).count()):
pd.value_counts(data["col"], sort=False) 返回一列

一个pakege下一定要__init__.py ,即使为空
查看python版本:import sys,platform >>>platform.architecture()

python -m pip install -U pip 更新pip
pip install --upgrade setuptools

数据切片:
data_ix = data.ix[:10][:],取前几个可以用head(n)
df.loc[[1, 5], ['b', 'c']] loc可以用列名
df.iloc[[0, 3, 5], 0:2] iloc 用的索引

df去掉某列:
1: df.drop('column_name',axis = 1,inplace = True)
2: df.drop([df.columns[[0,1,2]]],axis = 1,inplace = True)
3:df.dropna(axis=1, how='all') #去掉全部为空值的列
从众多列中选出特定的列
data_gene_102 = pd.read_clipboard(header = None) #一列数据,第零列,DataFrame格式
gene_102_list = list(data_gene_102[0]) #转为列表形式
data_102 = data_origin[gene_102_list] #直接在所需要的数据data[columns_list]

DataFrame转成字典后,columns为keys,读数据dataframe_dict.get('columns_name')[1]

按条件取data,data_ = data[data.columns == '*']
data_ = data.loc[(data.a == 'a')&(data.b == 'b')&(),["a","b","c"]] 还能选择列输出
data_ = data[[data.iloc[i][2] in list_a for i in data.index]]
data_.drop(['index'],aixs = 1,inplace = True)
data_ = data_.reset_index(range(data_.index.size))
\u24e2 转为中文显示.decode("unicode-escape")
重新索引
data_sendschedule = data_sendschedule.reset_index(range(data_sendschedule.index.size))
data_sendschedule.drop(['index'],aixs = 1 ,inpalce = True)
data中移动列:


列中替换值,可以多个换,可以写成字典的key换value
data['col'].replace([dict.keys()],[dict.values()],inplace = True)
Sereis增加行
series['Critical Value (%s)'%key] = value
空的DataFrame
可以先创建字典,再DataFrame([dict])
a = DataFrame([],index = ['1','2','3',4],columns = ['col1','col2'])
创建空字典:

dd = {}.fromkeys(car_Id_list,datetime.datetime.now()) keys可以用列表导入

当有一个列表list,list_ = ['a','c','d','b',],快速建立字典转DataFrame
dict_ = {}
for i in range(0,n): #列名为0到n, 也可以列名为列表里的值 for i in list:
dict_.update({str(i):list_[int(i)]) dict_.update({str(i):value})
DataFrame([dict_])
合并数据:
data_merged = data.merge(right=DataFrame, #往data里面合并DataFrame how='inner',left_on='col1',right_index=True, sort=False)
MAP函数
>>>deff(x):... 
return x * x
>>>r = map(f, [1,2,3,4,5,6,7,8,9])
>>>list(r)
map()接受两个参数,一个f()函数,一个iterateor,同时作用
filter()接受两个参数,一个boolean,一个iterator(),依次作用
g = lambda x : x * x 匿名函数
>>>g(3)
>>>6
int_2 = functools.partial(int ,int中的参数:base = 2),就是把某一个函数中的参数调好后重新命名。
python递归:
def method(self,a,b):
self.method(a,b)
apply()函数:
data.icol(1).apply(f) data.sex.apply(f) 在列上面用函数
保留小数点问题:
#后两位 print '%.2f'%103.4 显示为:103.40
round(num,2)#取两位,如果有零则不显示
反转数组:
a = [1,2,3,4,5] list(reversed(a)), a[::-1]
数据透视表:
impute_grps =data.pivot_table(values=["LoanAmount"],
index=["Gender","Married","Self_Employed"],aggfunc=np.mean)

pandas快速读取大数据:
read = pd.read_csv(path+'.csv',iterator = True)
loop = True
chunkSize = 100000
chunks = []
while loop:
try:
chunk = reader.get_chunk(chunkSize)
chunks.append(chunk)
except StopIteration:
loop = False
print("Iteration is stopped.")
df = pd.concat(chunks, ignore_index=True)#chunks为装有多个DataFrame的列表

df['Name'] = df['Name'].astype(np.datetime64)#转换类型
df.groupby(['NO','TIME','SVID']).count() # 分组
fullData = pd.merge(df, trancodeData)[['NO','SVID','TIME','CLASS','TYPE']] # 连接actions = fullData.pivot_table('SVID', columns='TYPE', aggfunc='count') # 透视表

a['col1'].map({'a':'男', 'b':'女'})


判断程序执行多长时间
#结束时间-开始时间
>>> import time
>>> start = time.time()
>>> end = time.time()
>>> print "read: %f s" % (end - start)
read: 6.760052 s

Anaconda 更新:


Python定时器(每5秒打印一次):

下面的t是第一次执行的时间为5秒,函数里的是没隔5秒执行
字符串转datetime
import datetime
dtstr = '2014-02-14 21:32:12'
a = datetime.datetime.strptime(dtstr, "%Y-%m-%d %H:%M:%S")
与当前时间比较 b = datetime.datetime.now() (b-a).days,hour,seconds
判断是不是整数
2.0.is_integer() True
2.3.is_integer() False
矩阵中求最大值的位置
raw, column = c.shape# get the matrix of a raw and column
_positon = np.argmax(c)# get the index of max in the a
m, n = divmod(_positon, column)
X矩阵的特征值和特征向量
a,b=numpy.linalg.eig(x)
list,[],列表去重:
set_result = list(set(result))
set_result.sort(result.index)
list排序sorted(['abc','cbd','abd'])
'sep'.join(i)的用法sep是分隔符,组成一条新的字符串
Python实现全排列:
import itertools
for i in itertools.permutations(string):
result.append(''.join(
Json数据与字典转换:
dict_data = json.loads(json_data)
json_data = json.dumps(dict_data)
with open(path,'w') as f:
f.write(json_data)
JSON存储与读写:
def store(data):    with open('data.json', 'w') as json_file:        json_file.write(json.dumps(data))def load():    with open('data.json') as json_file:        data = json.load(json_file)        return data
访问限制:
在Python中,变量名类似__xxx__的,也就是以双下划线开头,并且以双下划线结尾的,是特殊变量,特殊变量是可以直接访问的,不是private变量,所以,不能用__name____score__这样的变量名。
有些时候,你会看到以一个下划线开头的实例变量名,比如_name,这样的实例变量外部是可以访问的,但是,按照约定俗成的规定,当你看到这样的变量时,意思就是,“虽然我可以被访问,但是,请把我视为私有变量,不要随意访问”。
双下划线开头的实例变量是不是一定不能从外部访问呢?其实也不是。不能直接访问__name是因为Python解释器对外把__name变量改成了_Student__name,所以,仍然可以通过_Student__name来访问__name变量:

把print的结果保存到文件里:


matplotlib中文标题的支持:
from matplotlib.font_manager import FontPropertiesfont = FontProperties(fname=r"c:\windows\fonts\SimSun.ttc", size=14)
-----------------------------------------------------------------------
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #正常显示正负号

if __name__ == "__main__"
更好的例子是为了代码重用。
比如你现在写了一些程序,都存在单独的py文件里。有一天你突然想用1.py文件中的一个写好的函数来处理现在这个文件中的事物,你当然可以拷贝过来,你也可以把那个文件加上if __name__ == "__main__":这句话,然后从你现在写的文件中import 1就可以用1.py中的函数了。
a.py:
  1. #!/usr/bin/python  
  2. # Filename: a.py  
  3.   
  4. if __name__ == '__main__':  
  5.     print 'This program is being run by itself'  
  6. else:  
  7.     print 'I am being imported from another module'  
b.py:
  1. #!/usr/bin/python  
  2. # Filename: b.py  
  3.   
  4. import a  

运行:
  1. $ python2.7 a.py  
  2. This program is being run by itself  
  3. $ python2.7 b.py  
  4. I am being imported from another module  
总结: 每个Python模块都有它的__name__,如果__name__是'__main__',这说明这个模块被用户单独运行,导入的时候会先执行else:里面的

读数据分隔符:
读数据时候,read_table ,read_fwf中设置分隔符的参数,delimiter = ',',

*src Windows中的屏幕键盘
python画图:
fig = plt.figure(figsize=(5,5)) 设置画面大小
plt.subplot2grid((2,3),(0,0)) 两行三列图,此为第一行第一列图
plt.subplot2grid((2,3),(0,1)) 第一行第二列图
matplotlib中文标题的支持:
from matplotlib.font_manager import FontPropertiesfont = FontProperties(fname=r"c:\windows\fonts\SimSun.ttc", size=14)
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] #正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #正常显示正负号

fig=plt.figure()ax1=fig.add_subplot(141) 一张图有4列,第一张图
plt.legend([u"女性/低级舱"], loc='best') 各自的声明

ax2=fig.add_subplot(142, sharey=ax1) 第二张图
plt.legend([u"女性/高级舱"], loc='best') 各自的声明





0 0