【问题标题】:Get the specified set of columns from pandas dataframe [duplicate]从熊猫数据框中获取指定的列集[重复]
【发布时间】:2020-11-27 06:47:29
【问题描述】:

我使用手动选择熊猫数据框中的列

 df_final = df[['column1','column2'.......'column90']]

相反,我在列表中提供列名列表

 dp_col =  [col for col in df if col.startswith('column')]

但不确定如何使用此列表从源数据框中仅获取这些列集。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以将其用作要选择的列列表,因此:

    df_final = df[<b>[col for col in df if col.startswith('column')]</b>]

    字符串列表的“来源”并不重要,只要将字符串列表传递给下标,这将正常工作。

    【讨论】:

      【解决方案2】:

      使用带有布尔掩码的loc 访问:

      df.loc[:, df.columns.str.startswith('column')]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-29
        • 1970-01-01
        • 1970-01-01
        • 2021-03-20
        • 2022-11-15
        • 1970-01-01
        • 1970-01-01
        • 2015-05-10
        相关资源
        最近更新 更多