
python入门-函数
NO23412号菜狗
这个作者很懒,什么都没留下…
展开
专栏收录文章
- 默认排序
- 最新发布
- 最早发布
- 最多阅读
- 最少阅读
-
Python Numpy中reshape函数参数-1的含义
(100条消息) Python Numpy中reshape函数参数-1的含义_小红的博客-优快云博客原创 2021-07-05 23:21:55 · 155 阅读 · 0 评论 -
关于python bool判断出错的一些理解 stack最高回答
Theorandandpython statements requiretruth-values. Forpandasthese are considered ambiguous so you should use "bitwise"|(or) or&(and) operations:result = result[(result['var']>0.25) | (result['var']<-0.25)]These are overloaded for ...原创 2020-12-24 11:02:11 · 213 阅读 · 1 评论 -
python excel 读取 日期 数据 4 开头 乱码 解决的一个思路
apply加原创 2020-12-22 16:02:38 · 1270 阅读 · 0 评论 -
python dataframe 列 应用正则表达式 筛选
假设有如下的 DataFrame:现在需要增加一列,名字为选择原因,内容为在经营范围中进行搜索,如果发现含有设备、汽车、网络中的任何一个词的,就在选择原因中写上这个搜索到的词,否则不填。我们可以对列调用 apply 方法,使用正则表达式来进行匹配,假设 DataFrame 名称为 df,代码如下:import repattern = r'设备|汽车|网络'# 一行超人df['选择原因'] = df['经营范围'].apply(lambda s: ''.join(set(re.fin原创 2020-12-22 15:14:12 · 6746 阅读 · 2 评论 -
python 筛选 包含或不包含 某字符串 的方法列表
工作中数据的处理中往往会遇到筛选出不符合条件的或者不包含某个字符的dataframe,我们会如何去做呢?可能你会想到用python写一个函数,然后用panda的apply函数或者map函数来进行处理,不可否认这是一中方法,但是实际上pandas中已经给我们开发了这样的函数,那我们为什么不直接调用呢?首先看一下,怎么筛选出包含某些字符串的数据 #这是使用语法,模糊匹配 df[ df['通信名称'].str.contains('联通|移动|小灵通|电信')] #..原创 2020-12-21 16:18:59 · 23146 阅读 · 4 评论 -
python 列表 交并补 求解
在python中,数组可以用list来表示。如果有两个数组,分别要求交集,并集与差集,怎么实现比较方便呢?当然最容易想到的是对两个数组做循环,即写两个for循环来实现。这种写法大部分同学应该都会,而且也没有太多的技术含量,本博主就不解释了。这里给大家使用更为装bility的一些方法。老规矩,talk is cheap,show me the code#!/usr/bin/env python#coding:utf-8'''Created on 2016年6月9日@author: le原创 2020-12-18 09:52:41 · 612 阅读 · 0 评论 -
Python 疑难问题:[] 与 list() 哪个快?
# 方法一:使用成对的方括号语法list_a = []# 方法二:使用内置的 list()list_b = list()复制代码上面的两种写法,你经常使用哪一个呢?是否思考过它们的区别呢?让我们开门见山,直接抛出本文的问题吧:两种创建列表的 [] 与 list() 写法,哪一个更快呢,为什么它会更快呢?注:为了简化问题,我们以创建空列表为例进行分析。关于列表的更多介绍与用法说明,可以查看这篇文章1、 [] 是 list() 的三倍快对于第一个问题,使用timeit模块的 .原创 2020-12-18 06:09:02 · 239 阅读 · 0 评论 -
python 列表 返回 所有 元素 索引
在列表中使用index方法获取的只是第一个索引,比如想获取列表中的字符'A' >>> lst = ['A', 1, 4, 2, 'A', 3] >>> lst.index('A') 0 如果想获取所有'A'元素的索引列表,可以借助于下面的方法方法一: 常用方法 >>> def get_index1(lst=None, item=''): ... tmp = [] ... ta..原创 2020-12-14 18:03:27 · 4054 阅读 · 0 评论 -
python 输出 百分比
方式1:直接使用参数格式化:{:.2%}{:.2%}: 显示小数点后2位显示小数点后2位:>>> print('percent: {:.2%}'.format(42/50))percent: 84.00%1 2不显示小数位:{:.0%},即,将2改为0:>>> print('percent: {:.0%}'.format(42/50))percent: 84%1 2方式2:格式化为float,然后处理成%格式:{:.2f}%与方式.原创 2020-12-12 09:02:17 · 5181 阅读 · 0 评论 -
dataframe append 官方文档案例
pandas.DataFrame.applyDataFrame.apply(func,axis=0,raw=False,result_type=None,args=(),**kwds)[source]Apply a function along an axis of the DataFrame.Objects passed to the function are Series objects whose index is either the DataFrame’s index (ax...原创 2020-11-27 09:32:51 · 305 阅读 · 0 评论 -
np.arange() 详细教程
NumPyis the fundamental Python library for numerical computing. Its most important type is anarray typecalledndarray. NumPy offers a lot ofarray creation routinesfor different circumstances.arange()is one such function based onnumerical ranges. It...原创 2020-11-27 08:37:24 · 8821 阅读 · 0 评论 -
dataframe append 使用方法
pandas.DataFrame.appendDataFrame.append(other,ignore_index=False,verify_integrity=False,sort=False)[source]Append rows ofotherto the end of caller, returning a new object.Columns inotherthat are not in the caller are added as new columns.Par...原创 2020-11-25 09:56:32 · 4295 阅读 · 0 评论 -
dataframe 字符串切割
问题:现在手中有一表格,其中一列数据长成下列格式:三个元素挤在一个单元格中,现在需要把这三个元素进行分隔开,生成新的三列,该如何办?前面介绍了str.split()方法和re.split()方法,利用这两个方法任意一种方法,结合其他的方法,也可以完成工作,但是比较麻烦,具体的实现方式见文末。这里我们利用pandas的Series.str.split()方法可以很方便的实现。前面文章介绍了Python的内置方法str.split()和 re库中的re.split()方法,现在来介绍一下pand原创 2020-11-24 16:15:57 · 9118 阅读 · 0 评论 -
dataframe 转 字典
背景:将商品id以及商品类别作为字典的键值映射,生成字典,原为DataFrame# 创建一个DataFrame# 列值类型均为int型import pandas as pditem = pd.DataFrame({'item_id': [100120, 10024504, 1055460], 'item_category': [87974, 975646, 87974]}, index=[0, 1, 2])item# 将item_id,item_category两列数值转..原创 2020-11-22 16:59:13 · 1377 阅读 · 0 评论 -
python 数据分析案例——电影评分分析
import pandas as pdpd.options.display.max_rows=100unames = ['user_id', 'gender', 'age', 'occupation', 'zip']users=pd.read_table('D://01//users.dat',sep='::',header=None,names=unames,engine='python')usersrnames = ['user_id', 'movie_id', 'rating', 'ti.原创 2020-11-22 12:03:05 · 3379 阅读 · 1 评论 -
pandas 拆分 列 的一个特别例子
class_name列同时包含课程名称和同类群组编号。我想将栏分为两栏(名称,同类群组编号)从:| class_name || introduction to programming 1th || introduction to programming 2th || introduction to programming 3th || introduction to programming 4th || algorithms and data structure 1th || a.原创 2020-11-20 15:03:12 · 300 阅读 · 0 评论 -
时间数据处理之Arrow库
在处理数据的时候经常会碰见各种时间数据,但因为时间数据的格式不统一,所以导致数据处理的时候有一些麻烦。Python的标准库提供了相应模块,但可用性却不高,也不够人性化。本专栏之前已经有文章介绍过在R中如何处理时间数据(lubridate包),而Python中也有实现类似功能的包。这篇文章我们讲一下如何使用Python的第三方库Arrow来处理时间数据。Arrow提供一种易用的智能的方式来创建、操作、格式化和转换时间数据。基本使用Arrow处理时间数据时需要先将数据转为Arrow对象,Arrow可原创 2020-11-20 11:04:54 · 447 阅读 · 0 评论 -
NumPy 统计函数
NumPy 提供了很多统计函数,用于从数组中查找最小元素,最大元素,百分位标准差和方差等。 函数说明如下:numpy.amin() 和 numpy.amax()numpy.amin() 用于计算数组中的元素沿指定轴的最小值。numpy.amax() 用于计算数组中的元素沿指定轴的最大值。实例import numpy as np a = np.array([[3,7,5],[8,4,3],[2,4,9]]) print ('我们的数组是:') print (a) print ('\n')原创 2020-11-18 13:38:50 · 159 阅读 · 0 评论 -
numpy 算数函数
NumPy 算术函数NumPy 算术函数包含简单的加减乘除:add(),subtract(),multiply()和divide()。需要注意的是数组必须具有相同的形状或符合数组广播规则。实例import numpy as np a = np.arange(9, dtype = np.float_).reshape(3,3) print ('第一个数组:') print (a) print ('\n') print ('第二个数组:') b = np.array([10,10,10])...原创 2020-11-05 15:58:28 · 227 阅读 · 0 评论 -
urllib.error.URLError: <urlopen error [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。>
设置谷歌为默认浏览器原创 2020-10-23 11:36:39 · 3521 阅读 · 0 评论 -
python 字符串与datetime 相互转换
from datetime import datetimestam1=datetime(2008,1,23)str(stam1)stam1.strftime('%Y-%m-%d')stam1.strftime('%w')value = '2017/10/7'datetime.strptime(value,'%Y/%m/%d')原创 2020-10-21 11:56:34 · 240 阅读 · 0 评论 -
显示DataFrame的全部行和列
如果想要指定最大的行数和列数,代码如下: pd.set_option('max_rows', 5) pd.set_option('max_columns', 5) 如果想要直接指定显示所有的行和列,代码如下: pd.options.display.max_columns = None pd.options.display.max_rows = None ...原创 2020-10-20 20:33:37 · 1608 阅读 · 0 评论 -
python groupby 站总体百分比
import pandas as pdimport numpy as npdf = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3, 'office_id':list(range(1,7)) * 2, 'sales': [np.random.randint(100000, 999999) for _ in rang.原创 2020-10-20 17:05:27 · 843 阅读 · 0 评论 -
python 最好的 时间处理教程
https://blog.youkuaiyun.com/mhywoniu/article/details/78514664原创 2020-10-20 08:00:57 · 101 阅读 · 0 评论 -
python中for _ in range () 中‘_‘的意思
a=0b=1for _ in range(20): (a,b)=(b,a+b) print(a,end=',')其中’_’ 是一个循环标志,也可以用i,j 等其他字母代替,下面的循环中不会用到,起到的是循环此数的作用原创 2020-10-18 08:55:08 · 790 阅读 · 0 评论 -
pandas sort_values
pandas排序的方法有很多,sort_values表示根据某一列排序pd.sort_values("xxx",inplace=True) 表示pd按照xxx这个字段排序,inplace默认为False,如果该值为False,那么原来的pd顺序没变,只是返回的是排序的...原创 2020-10-15 21:38:55 · 216 阅读 · 0 评论 -
pandas 多重索引 multiIndex
import pandas as pddf = pd.DataFrame({'class':['A','A','A','B','B','B','C','C'], 'id':['a','b','c','a','b','c','a','b'], 'value':[1,2,3,4,5,6,7,8]})dfdf=df.set_index(['class','id'])df.loc[('A',slice(None)),:]df.l.原创 2020-10-12 16:43:37 · 191 阅读 · 0 评论 -
python 将excel 数字日期转化为正常
import pandas as pdimport datetimedata_tr=pd.read_excel('D:\\train.xlsx')data_trdata_tr.columnsdata_tr['合同签订时间']def date_tran(dates): delta=datetime.timedelta(days=dates) date_1=datetime.datetime.strptime('1899-12-30','%Y-%m-%d')+delta .原创 2020-10-12 10:49:28 · 1130 阅读 · 0 评论 -
dataframe 不显示科学计数法
pd.set_option('display.float_format', lambda x: '%.2f' % x)原创 2020-10-09 15:41:11 · 3251 阅读 · 0 评论 -
python dataframe 写入 excel
项目中用到把DateFrame写入Excel,其中pandas中的几个参数非常有用。这里以实例说明: import pandas as pd #create some Pandas DateFrame from some data df1=pd.DataFrame({'Data1':[1,2,3,4,5,6,7]}) df2=pd.DataFrame({'Data2':[8,9,10,11,12,13]}) df3=pd.DataFrame(..原创 2020-10-08 14:43:16 · 9164 阅读 · 0 评论 -
python 生成随机数
import numpy as npimport randomnp.random.rand(10)np.random.randn(10)np.random.randint(1,10,size=5)np.random.random_integers(1,10,size=6)t1=np.arange(10)t1np.random.shuffle(t1)t1np.random.permutation(5)#整数random.randint(1,5)random.random()ran.原创 2020-10-08 11:55:17 · 167 阅读 · 0 评论 -
python 结果保留 小数
a = 12.345print('%.2f'%a)round(a,2)from decimal import Decimal# Decimal(a).quantize(Decimal('0.00'))t1=Decimal(a).quantize(Decimal('0.00'))t1a1=pd.DataFrame(index=['a1'],columns=['b1'])a1a1.loc['a1']=t1a1a1=12.45str(a1).split('.')[0]+'.'+str.原创 2020-10-06 13:01:19 · 476 阅读 · 0 评论 -
pycharm 一直 connecting to console 解决方案
国内网上的基本都不太好使国外也没什么准确方案快速方案删除所有的anaconda path 变量然后重装之后正常原创 2020-10-03 19:31:37 · 656 阅读 · 0 评论 -
关于python的分组函数
import pandas as pdimport numpy as npdf00 = pd.DataFrame({'key1':['a','a','b','b','a'],'key2':['one','two','one','two','one'],'data1':np.random.randn(5),'data2':np.random.randn(5)})df00group1=df00.groupby(['key1','key2'])# print(group1)[x for x in g.原创 2020-09-28 15:01:53 · 309 阅读 · 0 评论 -
python 去极值方法(三种举例)
import numpy as npimport pandas as pdfrom pandas import Seriesdef filter_extereme_MAD(series,n): median=series.quantile(0.5) n1_median=((series-median).abs()).quantile(0.50) max_rangef=median+n*n1_median min_range=median-n*n1_median .原创 2020-09-23 16:52:10 · 3536 阅读 · 0 评论 -
anaconda linux安装
1.从官网下载Linux版本的anaconda,https://www.anaconda.com/download/2.安装anaconda,执行下列命令bash Anaconda2-5.0.0.1-Linux-x86_64.sh3.在安装过程中会显示配置路径Prefix=/home/jsy/anaconda2/4.安装完之后,运行python,仍是ubuntu自带的python信息,需自己设置下环境变量5.在终端输入$sudo gedit /etc/profile,打...原创 2020-09-23 09:46:40 · 188 阅读 · 0 评论 -
Numpy 中clip函数的使用
import numpy as npx1=[1,2,3,43,4,3,2,3,3,6,7,8]cl1=np.clip(x1,3,10)cl1原创 2020-09-17 14:52:44 · 205 阅读 · 0 评论 -
python获取数组中最多的元素(用max函数)
sample1 = [1,2,3,3,3,4,5,5]max(set(sample1),key=sample1.count)原创 2020-09-01 21:19:22 · 599 阅读 · 0 评论 -
python 匿名函数
有没有想过定义一个很短的回调函数,但又不想用def的形式去写一个那么长的函数,那么有没有快捷方式呢?答案是有的。python 使用 lambda 来创建匿名函数,也就是不再使用 def 语句这样标准的形式定义一个函数。匿名函数主要有以下特点:lambda 只是一个表达式,函数体比 def 简单很多。 lambda 的主体是一个表达式,而不是一个代码块。仅仅能在 lambda ...原创 2020-03-04 21:35:54 · 201 阅读 · 0 评论 -
Python 正则re模块之compile()和findall()
import res = "adfad asdfasdf asdfas asdfawef asd adsfas "reo1=re.compile('((\w+)\s+\w+)')reo1.findall(s)reo2=re.compile('(\w+)\s+\w+')reo2.findall(s)reo3=re.compile('\w+\s+\w+')reo3.findall(s)...原创 2020-02-27 10:29:36 · 681 阅读 · 0 评论