通过整数访问行和通过标签 Pandas 访问列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45330271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:06:13  来源:igfitidea点击:

Access Rows by integers and Columns by labels Pandas

pythonpandassklearn-pandas

提问by sir_osthara

My data is like this:

我的数据是这样的:

[First row is headers]

[第一行是标题]

Name,Email,Age
Sachith,[email protected],23
Sim,[email protected],234
Yoshi,[email protected],2345
sarla,[email protected],234

I would like to access elements such that rows are specified as integers and columns by labels. i.e for SimI would like to access it as [1,'Name']and so-on

我想访问元素,以便通过标签将行指定为整数和列。即对SIM卡,我想访问它[1,“名称”]等上

My question is should I use locor ix?

我的问题是我应该使用loc还是ix

Looking at the documentation, I am confused as to what is a pandas index? Is it used to access rows or columns or both? When I try to print the indices of this data, I get a (4,) dtype=int64 array of [0,1,2,3]. So , are columns not part of the index?

查看文档,我对什么是Pandas索引感到困惑?它是用来访问行或列还是两者兼而有之?当我尝试打印这些数据的索引时,我得到一个 [0,1,2,3] 的 (4,) dtype=int64 数组。那么,列不是索引的一部分吗?

回答by jezrael

Use locor iloc, because ixis deprecated.

使用loc或者iloc,因为ix弃用

print (df)
      Name             Email   Age
0  Sachith      [email protected]    23
1      Sim      [email protected]   234
2    Yoshi  [email protected]  2345
3    sarla   [email protected]   234

#select by label 1 and label Name    
a = df.loc[1, 'Name']
print (a)
Sim

But if need select index by position (need iloc) and columns by labels (need loc) together:

但是如果需要按位置(need iloc)选择索引和按标签(need loc)列选择一起:

df = df.set_index('Email')
print (df)
                     Name   Age
Email                          
[email protected]      Sachith    23
[email protected]          Sim   234
[email protected]    Yoshi  2345
[email protected]     sarla   234

get label of second index by df.index[1]:

通过以下方式获取第二个索引的标签df.index[1]

a = df.loc[df.index[1], 'Name']
print (a)
Sim

Or get position of label by get_loc:

或通过get_loc以下方式获取标签位置:

a = df.iloc[1, df.columns.get_loc('Name')]
print (a)
Sim