python3a 之 循环与加速(for循环,list 简化,iterrows, enumerate )

1.  map 的用法: 替代for循环,辅助加速

map(function, list)

简写

 map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数

[1, 4, 9, 16, 25]

提供了两个列表,对相同位置的列表数据进行相加

>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])

[3, 7, 11, 15, 19]

以def写复杂函数

pd.Series(map(lambda x: str(end_date3[x]), list(df1['contract'])))

end_date

df1['contract']

最终结果:

map函数的用法:

def multiply(x):

return (x*x)

def add(x):

return (x+x)

funcs = [multiply, add]

for i in range(5):

    value = map(lambda x: x(i), funcs)

    print(list(value))

# Output:

# [0, 0]

# [1, 2]

# [4, 4]

# [9, 6]

# [16, 8]

2. 制造dict和key

pos_signal = {}

3. 善用if in

        def find_index_constitutes(code):

            key = str(code[0]) + '|' + str(code[1])

            if key in index_htable:

                return index_htable[key]

            else:

                return '其他'

4. 多进程

pool.join 是按顺序输出。

5、 For 循环基本用法

将所有的数据输出:

res=[]

res=pd.DataFrame() 【如果是矩阵】

for i in ... #循环处理文档的每一行

     .........

     line=..... #line为每一行的处理结果

     res.append(line) #如果前面加上res=可能会报错

print(res) #res就是所需要的结果

For 循环的参数:   for i in range( len(X)):

range:(start, stop[, step])  算前不算后

range(10)       

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(1, 11)  

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

range(0, 30, 5) 

[0, 5, 10, 15, 20, 25]

size:len(X)

输出行数:x.shape[0]

输出列数:x.shape[1]

将dataframe拼接

result = [] 

for t in dates: 

    result.append(func(t)) 

print (pd.concat(result, axis=1)) 

将list中多个dataframe拼接成dataframe,先append,再concat

for t in dates: 

   expseason2.append(expseason1)

    expseaso3=pd.concat(expseason2,axis=0)

6. 反向循环

for t in reversed(range(col - 1)):

[9876543210]

7. iterrows 循环 :行循环

创造样例数据

import pandas as pd

import numpy as np

df = pd.DataFrame(np.random.randn(2,2), columns = list('AB'))

for x, y in df.iterrows():

print(x)

print(y)

y['A']

8. enumerate 循环: 行列名称

for x, y in df. enumerate():

      print(x)

print(y)

9. list中简化for 循环

重复

date = [1,2,3]

 [x for x in date for i in range(3)]

累加+for简化:

n=index_price.shape[0]

count=[0 for x in range(0,n)]

10. 通过 dict 制造key,搜索双标签对应的值

   index_htable={}    

    for _,row in  idc.iterrows():   #按行循环

        key = str(row[u'股票代码']) + '|' +str(row[u'日期']) #根据不同 的索引重新制作键值

        value = str(row[u'指数代码'])

        if value == '000300.SH':

            value = '沪深300'

        else:

            value = '其他'

        index_htable[key] = value # 对值重新定义索引和名称

    def find_index_constitutes(code):

        key = str(code[0]) + '|' + str(code[1])  

        if key in index_htable:  # 搜寻键对应的值

            print('found key',key,index_htable[key])

            return index_htable[key]

        else:

            return '其他'

11. 使用生成器占用更少资源yield

# generator version

def fibon(n):

    a = b = 1

for i in range(n):

yield a

        a, b = b, a + b

for x in fibon(1000000):

print(x)

用这种方式,我们可以不用担心它会使用大量资源。然而,之前如果我们这样来实现的话,这也许会在计算很大的输入参数时,用尽所有的资源

def fibon(n):

    a = b = 1

    result = []

for i in range(n):

        result.append(a)

        a, b = b, a + b

return result

def generator_function():

for i in range(3):

yield i

使用next() 获取下一个元素。

gen = generator_function()

print(next(gen))

# Output: 0

print(next(gen))

# Output: 1

print(next(gen))

# Output: 2

print(next(gen))

# Output: Traceback (most recent call last):

#            File ""

12. iter: 迭代

my_string = "Yasoob"

my_iter = iter(my_string)

next(my_iter)

# Output: 'Y'

13. reduce

当需要对一个列表进行一些计算并返回结果时,Reduce 是个非常有用的函数。举个例子,当你需要计算一个整数列表的乘积时。通常在 python 中你可能会使用基本的 for 循环来完成这个任务。

from functools import reduce

product = reduce( (lambda x, y: x * y), [1234] )

# Output: 24

14. filter过滤

number_list = range(-55)

less_than_zero = filter(lambda x: x < 0, number_list)

print(list(less_than_zero))  

# Output: [-5, -4, -3, -2, -1]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,可以使用enumerate()函数在for循环中同时获取元素和对应的索引值。enumerate()函数将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,通过遍历这个索引序列,可以获取到元素和对应的索引值。这个函数的语法如下:enumerate(sequence, start=0)。其中,sequence是一个序列、迭代器或其他支持迭代对象,start是可选参数,表示索引的起始位置,默认为0。函数返回的是一个enumerate对象,是一个可迭代对象,可以通过遍历取出元素和索引值。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [python 使用enumerate()函数详解](https://blog.csdn.net/jh035/article/details/128077895)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [python遍历序列enumerate函数浅析](https://download.csdn.net/download/weixin_38742124/14861800)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值