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

问题描述 投票:0回答:2

目标是获取一个像这样打印的数据框:

     Tag  Posts
0  metal  27323
1 plastic 11192

但只能获取值:

27323

重要提示:我无法使用数值查找行。行必须以标签名称定位,然后从该行中检索“返回”的列以返回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'>

感谢您抽出宝贵的时间来帮助我。

python-3.x pandas dataframe
2个回答
0
投票

您不正确地读取了文件。不要传递names='metal'选项,它会使其中一列具有名称“ metal”而不是“ Tag”。解决此问题后,即可找到答案:

read_csv.loc[read_csv.Tag == 'metal', 'Posts']
# 0    27323

0
投票
tag = ['metal', 'plastic']
num = ['27323', '11192']

df = pd.DataFrame(
    {
        'num': num,

    },index=tag)

print(df.loc['plastic','num'])

这将满足您的需求。

© www.soinside.com 2019 - 2024. All rights reserved.