【问题标题】:How do I know a row label of a series of pandas dataframe?我如何知道一系列熊猫数据框的行标签?
【发布时间】:2020-07-27 02:26:38
【问题描述】:

给出了一个 CSV 文件。我应该将数据框行的行标签的名称打印为字符串输出。我该怎么做?

import pandas as pd
df= pd.read_csv('olympics.csv', index_col=0, skiprows=1)
s= df.loc[df['Gold'].idxmax()]
return s.index

这里的“Gold”是一个随机的列索引名称。我一直在尝试使用此代码。但它只打印列索引。但我需要将行索引输出打印为字符串。

【问题讨论】:

  • df.loc[df['Gold'].idxmax()].name??

标签: python pandas dataframe csv series


【解决方案1】:
df = pd.DataFrame({'id':['1','2','3','4','5','6','7','8'], 
                     'A':['foo','bar','foo','bar','foo','bar','foo','foo'],  
                     'C':[10, 10, 10, 30, 50, 60, 50,  8], 
                     'D':[9, 8, 7, 6, 5, 4, 3, 2]},
                    index = list('abcdefgh'))

idxmax() 返回行索引,

>>> df['C'].idxmax()
'f'

选择该行会生成一个 Series,其名称是该行的索引。

>>> df.loc[df['C'].idxmax()]
id      6
A     bar
C      60
D       4
Name: f, dtype: object

>>> df.loc[df['C'].idxmax()].name
'f'

【讨论】:

    猜你喜欢
    • 2020-06-03
    • 1970-01-01
    • 2018-11-06
    • 2020-01-11
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    相关资源
    最近更新 更多