【问题标题】:Get a pandas column name as a string以字符串形式获取 pandas 列名
【发布时间】:2021-02-25 18:08:23
【问题描述】:

我有一个包含多列和多行的数据框。我正在尝试查找包含条目'some_string' 的列。我设法做到了这一点

col = df.columns[df.isin(['some_string']).any()]

我想将col 作为一个字符串,但它是以下类型

In [47]:
print(col)

Out[47]:
Index(['col_N'], dtype='object')

那么我怎样才能只返回'col_N'?我只是找不到答案!天呐

【问题讨论】:

  • 这是因为多个列可以有some_string 因此返回一个列表。如果您只需要第一列名称,请使用 df.columns[df.isin(['some_string']).any()][0]

标签: python pandas dataframe slice


【解决方案1】:

您可以将您的输出视为一个列表。如果你只有一场比赛,你可以为

print(col[0])

如果您有一个或多个并且想要打印全部,您可以将其转换为列表:

print(list(col))

或者你只能将 col 的值传递给 print:

print(*col)

【讨论】:

    【解决方案2】:

    我认为类型转换会有所帮助

    list_of_columns = list(df.columns)
    

    【讨论】:

      猜你喜欢
      • 2021-12-05
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多