按整数访问行,按标签访问列 Pandas
Access Rows by integers and Columns by labels Pandas
我的数据是这样的:
[第一行是headers]
Name,Email,Age
Sachith,ko@gmail.com,23
Sim,sm@gmail.com,234
Yoshi,yosi@hotmail.com,2345
sarla,sarla@gmail.com,234
我想访问这样的元素,即行被指定为整数,列被标签指定。即对于 Sim 我想以 [1,'Name'] 和 so-on
的形式访问它
我的问题是我应该使用 loc 还是 ix?
查看文档,我对什么是 pandas 索引感到困惑?它用于访问行或列还是两者?当我尝试打印此数据的索引时,我得到一个 [0,1,2,3] 的 (4,) dtype=int64 数组。那么,列不是索引的一部分吗?
使用loc
or iloc
, because ix
is deprecated.
print (df)
Name Email Age
0 Sachith ko@gmail.com 23
1 Sim sm@gmail.com 234
2 Yoshi yosi@hotmail.com 2345
3 sarla sarla@gmail.com 234
#select by label 1 and label Name
a = df.loc[1, 'Name']
print (a)
Sim
但如果需要 select 按位置索引(需要 iloc
)和按标签列(需要 loc
)一起:
df = df.set_index('Email')
print (df)
Name Age
Email
ko@gmail.com Sachith 23
sm@gmail.com Sim 234
yosi@hotmail.com Yoshi 2345
sarla@gmail.com sarla 234
通过df.index[1]
获取第二个索引的标签:
a = df.loc[df.index[1], 'Name']
print (a)
Sim
或通过get_loc
获取标签位置:
a = df.iloc[1, df.columns.get_loc('Name')]
print (a)
Sim
我的数据是这样的:
[第一行是headers]
Name,Email,Age
Sachith,ko@gmail.com,23
Sim,sm@gmail.com,234
Yoshi,yosi@hotmail.com,2345
sarla,sarla@gmail.com,234
我想访问这样的元素,即行被指定为整数,列被标签指定。即对于 Sim 我想以 [1,'Name'] 和 so-on
的形式访问它我的问题是我应该使用 loc 还是 ix?
查看文档,我对什么是 pandas 索引感到困惑?它用于访问行或列还是两者?当我尝试打印此数据的索引时,我得到一个 [0,1,2,3] 的 (4,) dtype=int64 数组。那么,列不是索引的一部分吗?
使用loc
or iloc
, because ix
is deprecated.
print (df)
Name Email Age
0 Sachith ko@gmail.com 23
1 Sim sm@gmail.com 234
2 Yoshi yosi@hotmail.com 2345
3 sarla sarla@gmail.com 234
#select by label 1 and label Name
a = df.loc[1, 'Name']
print (a)
Sim
但如果需要 select 按位置索引(需要 iloc
)和按标签列(需要 loc
)一起:
df = df.set_index('Email')
print (df)
Name Age
Email
ko@gmail.com Sachith 23
sm@gmail.com Sim 234
yosi@hotmail.com Yoshi 2345
sarla@gmail.com sarla 234
通过df.index[1]
获取第二个索引的标签:
a = df.loc[df.index[1], 'Name']
print (a)
Sim
或通过get_loc
获取标签位置:
a = df.iloc[1, df.columns.get_loc('Name')]
print (a)
Sim