按列索引而不是列名称调用数据框中的列 - pandas

时间:2016-03-30 17:52:31

标签: python pandas dataframe

如何使用数据框中的索引而不是名称来调用代码中的列。

例如,我的数据框df包含a列,bc

我可以使用像df['a']这样的列索引来调用df[1],而不是调用;(function(){ $(document).ready(function() { $( '.dropdown' ).hover( function(){ $(this).children('.submenu').slideDown(200); }, function(){ $(this).children('.submenu').slideUp(200); } ); }); })(); 吗?

2 个答案:

答案 0 :(得分:3)

您可以使用iloc

df.iloc[:, 0]

示例:

>>> df
   a  b  c
0  1  4  7
1  2  5  8
2  3  6  9

>>> df['a']
0    1
1    2
2    3
Name: a, dtype: int64

>>> df.iloc[:, 0]
0    1
1    2
2    3
Name: a, dtype: int64

答案 1 :(得分:0)

indexing and selecting data 文档提到索引运算符 [] 的提供更多是为了方便。 ilocloc 方法在数据帧上提供更明确的索引操作。

注意: 索引在熊猫中有自己的含义。因此,在引用数字索引(如数组索引)时,最好使用 interger position(或仅使用 position)。

>>> df
   a  b
0  1  4
1  2  5
2  3  6

>>> df['a']
0    1
1    2
2    3
Name: a, dtype: int64

按整数位置访问行和列

df.iloc[row_start_position:row_end_position, col_start_position: col_end_position]

>>> df.iloc[0:3, 0:1]
   a
0  1
1  2
2  3

>>> df.iloc[:, 0]  # use of implicit start and end
0    1
1    2
2    3
Name: a, dtype: int64

按标签访问行和列

df.loc[row_start_label:row_end_label, col_start_label: col_end_label]

注意:在这个例子中,恰好行标签和行位置是相同的,它们是整数0, 1, 2

>>>  df.loc[0:2, 'a':'a']
   a
0  1
1  2
2  3

>>> df.loc[:, 'a'] # use of implicit start and end
0    1
1    2
2    3
Name: a, dtype: int64

查看如何Query / Select / Slice Data了解更多详情。

相关问题