pandas 学习汇总3 - Series,DataFrame迭代iter( tcy)
发布日期:2021-06-29 14:47:58 浏览次数:2 分类:技术文章

本文共 1841 字,大约阅读时间需要 6 分钟。

迭代iter   2018/12/1    =======================================================================1.基本iteration()产生:#系列:值;DataFrame:列标签;面板:项目标签# 迭代Series类似数组,迭代产生值。其他数据结构如DataFrame遵循迭代对象“键”的类似dict    s = pd.Series( [1,2,3],index=['a', 'b', 'c'])for col in s:    print(col,end=",")  #1 ,2 ,3,df = pd.DataFrame({'col1' : [1,2,3], 'col2' : [4,5.0,6]},index=['a', 'b', 'c'])for col in df:       print(col)           # col1 col2=======================================================================    2.iteritems 类似dict遍历键值对:# 系列 :(索引,标量值)对;DataFrame :(列,系列)对;面板 :( item,DataFrame)对    for index,value in s.iteritems():    print('(%s,%s)'%(index,value,),end='') # (a,1)(b,2)(c,3)    for col,s0 in df.iteritems():    print(col)    print(s0)# col1# a    1# b    2# c    3# Name: col1, dtype: int64# col2# a    4.0# b    5.0# c    6.0# Name: col2, dtype: float64=====================================================================3.迭代DataFrame行    iterrows()迭代DataFrame行返回迭代器,产生索引值及每行Series;没有保留跨行dtypesitertuples()返回迭代器,为DataFrame每一行产生一个namedtuple。    # 元组的第一个元素是行的相应索引值,而其余值是行值。    #  itertuples()保留值的数据类型快于iterrows()    # 实例1:for row_index, row in df.iterrows():       print('%s\n%s' % (row_index, row))       #  a# col1    1.0# col2    4.0# Name: a, dtype: float64# b# col1    2.0# col2    5.0# Name: b, dtype: float64# c# col1    3.0# col2    6.0# Name: c, dtype: float64    # 实例2:for row in df.itertuples():       print(row)    # Pandas(Index='a', col1=1, col2=4.0)# Pandas(Index='b', col1=2, col2=5.0)# Pandas(Index='c', col1=3, col2=6.0)======================================================================4.备注    # pandas对象迭代通常很慢。在许多情况下,不需要在行上迭代,用以下方法之一避免:    # 矢量化:内置方法或NumPy函数(布尔)索引,若无函数可用最好用apply()而不是迭代值。    # 性能很重要用cython或numba编写内部循环。    警告    迭代器返回副本而不是视图,写入它将不起作用!======================================================================

转载地址:https://chunyou.blog.csdn.net/article/details/84676109 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:pandas 4 - 排序( tcy)
下一篇:pandas 学习汇总2 - 数据帧DataFrame创建(12种方法)( tcy)

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月14日 13时09分02秒