Pandas

Pandas,第1张

对于 Series 而言,您可以把它当做一维数组进行遍历 *** 作;而像 DataFrame 这种二维数据表结构,则类似于遍历 Python 字典。

for遍历

在 Pandas 中通过for遍历后,Series 可直接获取相应的 value,而 DataFrame 则会获取列标签。

# 示例如下:
import pandas as pd
import numpy as np
N=20
df = pd.DataFrame({
'A': pd.date_range(start='2016-01-01',periods=N, freq='D'),
'x': np.linspace(0, stop=N-1,num=N),
'y': np.random.rand(N),
'C': np.random.choice(['Low','Medium','High'],N).tolist(),
'D': np.random.normal(100, 10, size=(N)).tolist()
})

for col in df:
    print (col)

# 输出结果:
A
x
y
C
D
内置迭代方法

遍历 DataFrame 的每一行,有下列函数:

  • 1) iteritems():以键值对 (key,value) 的形式遍历;
  • 2) iterrows():以 (row_index,row) 的形式遍历行;
  • 3) itertuples():使用已命名元组的方式对行遍历。
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(4,3),columns=['col1','col2','col3'])
print(df)

输出结果:
       col1      col2      col3
0 -0.319301  0.205636  0.247029
1  0.673788  0.874376  1.286151
2  0.853439  0.543066 -1.759512
1) iteritems()

以键值对的形式遍历 DataFrame 对象,以列标签为键,以对应列的元素为值。

for key,value in df.iteritems():
    print (key,value)

输出结果:
col1 
0 -0.319301
1  0.673788
2  0.853439
Name: col1, dtype: float64
col2 
0  0.205636
1  0.874376
2  0.543066
Name: col2, dtype: float64
col3 
0  0.247029
1  1.286151
2 -1.759512
Name: col3, dtype: float64
2) iterrows()

该方法按行遍历,返回一个迭代器,以行索引标签为键,以每一行数据为值。示例如下:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3,3),columns = ['col1','col2','col3'])

for row_index,row in df.iterrows():
    print (row_index,row)

输出结果:
0
col1   -0.319301
col2    0.205636
col3    0.247029
Name: 0, dtype: float64
1
col1    0.673788
col2    0.874376
col3    1.286151
Name: 1, dtype: float64
2
col1    0.853439
col2    0.543066
col3   -1.759512
Name: 2, dtype: float64

注意:iterrows() 遍历行,其中 0,1,2 是行索引而 col1,col2,col3 是列索引。

3) itertuples

itertuples() 同样将返回一个迭代器,该方法会把 DataFrame 的每一行生成一个元组,示例如下:

for row in df.itertuples():
    print(row)

输出结果:
Pandas(Index=0, col1=0.253902385555437, col2=0.9846386610838339, col3=0.8814786409138894)
Pandas(Index=1, col1=0.186673672989089, col2=0.5954745800963542, col3=0.0461448862299109)
Pandas(Index=2, col1=0.306629787541209, col2=0.1798421092872353, col3=0.8573031941082285)

迭代返回副本

迭代器返回的是原对象的副本,所以在迭代过程中修改元素值,不会影响原对象,这点需要注意。

for index, row in df.iterrows():
    row['a'] = 15
    print (df)

输出结果:
       col1      col2      col3
0 -0.319301  0.205636  0.247029
1  0.673788  0.874376  1.286151
2  0.853439  0.543066 -1.759512

由上述示例可见,原对象df没有受到任何影响。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/866727.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-12
下一篇 2022-05-12

发表评论

登录后才能评论

评论列表(0条)

保存