python3 熊猫获取特定的行和特定的列



目标是获取如下所示的数据框:

Tag  Posts
0  metal  27323
1 plastic 11192

但只获取值:

27323

重要提示:我不能使用数值来查找行。必须按标记名称定位该行,然后从该行检索"POSTS"列以返回 27323

这是我一直在尝试的:

tag = ['metal', 'plastic']
num = ['27323', '11192']
df = pd.DataFrame(
{
'Tag': tag,
'Posts': num,
})
# Then write data to csv file
df.to_csv('tag_data.csv', index=False)
# Read that csv file but only retrieve the row for 'metal'
read_csv = pd.read_csv('tag_data.csv', names='metal')
# Then retrieve the column for 'num'
print(read_csv.loc[0,'Posts'])

这将返回此错误:

"cannot do {form} indexing on {type(self)} with these "
TypeError: cannot do label indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <class 'int'>

如果可以的话,感谢您花时间帮助我。

您错误地读取了文件。不要传递names='metal'选项,它会使其中一列的名称为"金属"而不是"标签"。一旦你解决了这个问题,这就是答案:

read_csv.loc[read_csv.Tag == 'metal', 'Posts']
# 0    27323
tag = ['metal', 'plastic']
num = ['27323', '11192']
df = pd.DataFrame(
{
'num': num,
},index=tag)
print(df.loc['plastic','num'])

这将为您提供所需的内容。

最新更新