python - 按整数访问行,按标签访问列 Pandas

标签 python pandas sklearn-pandas

我的数据是这样的:

[第一行是标题]

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'] 等方式访问它

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

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

最佳答案

使用lociloc , 因为 ixdeprecated .

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

但如果同时需要按位置选择索引(需要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

关于python - 按整数访问行,按标签访问列 Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45330271/

相关文章:

python - 使用 savedmodel simple_save 和 tensorflow keras 预处理输入

python - for循环在 Pandas 中使用iterrows

python - 基本 Pandas matplotlib 绘图

python - 如何使用 sklearn k-means 聚类根据特征之间的相关性对特征进行聚类

python - Sklearn 0.20+ 的交叉验证?

Python 3 使用 Matplotlib 添加颜色条

python - 将值分配给由正则表达式获得的一组列

python - 将 tfidf 附加到 pandas 数据框

带有字符串列表的 Python DataFrame 列不会展平

python - 值错误 : time data- does not match format - Pandas