One - One Code All

Blog Content

详解pandas获取Dataframe元素值遍历取值的几种方法

Python 统计学-科学计算   2018-03-28 23:47:18

可以通过遍历的方法:


选择列

使用类字典属性,返回的是Series类型

data[‘w']

遍历Series

for index in data['w'].index:

time_dis = data['w'].get(index)


pandas.DataFrame.at

根据行索引和列名,获取一个元素的值

>>> df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]],

...     columns=['A', 'B', 'C'])

>>> df

 A B C

0 0 2 3

1 0 4 1

2 10 20 30


>>> df.at[4, 'B']

2


或者

>>> df.iloc[5].at['B']

4


pandas.DataFrame.iat

根据行索引和列索引获取元素值


>>> df = pd.DataFrame([[0, 2, 3], [0, 4, 1], [10, 20, 30]],

...     columns=['A', 'B', 'C'])

>>> df

 A B C

0 0 2 3

1 0 4 1

2 10 20 30

1

2

>>> df.iat[1, 2]

1


或者

>>> df.iloc[0].iat[1]

2


pandas.DataFrame.loc

选取元素,或者行

>>> df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],

...  index=['cobra', 'viper', 'sidewinder'],

...  columns=['max_speed', 'shield'])

>>> df

   max_speed shield

cobra    1  2

viper    4  5

sidewinder   7  8


选取元素

>>> df.loc['cobra', 'shield']

2


选取行返回一个series

>>> df.loc['viper']

max_speed 4

shield  5

Name: viper, dtype: int64


选取行列返回dataframe


>>> df.loc[['viper', 'sidewinder']]

   max_speed shield

viper    4  5

sidewinder   7  8

  

pandas.DataFrame.iloc

>>> mydict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},

...   {'a': 100, 'b': 200, 'c': 300, 'd': 400},

...   {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]

>>> df = pd.DataFrame(mydict)

>>> df

  a  b  c  d

0  1  2  3  4

1 100 200 300 400

2 1000 2000 3000 4000


按索引选取元素

>>> df.iloc[0, 1]

2


获取行的series

>>> type(df.iloc[0])

>>> df.iloc[0]

a 1

b 2

c 3

d 4

Name: 0, dtype: int64



上一篇:python logger日志通用配置文件
下一篇:TensorRT的集成加速TensorFlow的推理

The minute you think of giving up, think of the reason why you held on so long.