【问题标题】:Get a list of column headers based on string list根据字符串列表获取列标题列表
【发布时间】:2020-03-22 15:01:42
【问题描述】:

问题:我有一个数据框,其中包含各种列标题,其名称包含多个字符串的变体:“Fee_code”、“zip_code”等,还有一些其他的:“street_address”、“violation_street address”等。

预期结果:包含与关键字匹配的所有列标题的列表:费用、地址、代码、名称以及可能基于我将处理的特定文件的其他内容。请注意,我确实想保留“机构名称”列标题。

解决方案:我想出了这个函数来列出上面列出的所有字符串 - 以及更多 - :

def drop_cols(df):
    list1= list(df.filter(like='nam', axis=1))
    list1.remove('agency_name')
    list2= list(df.filter(like='add', axis=1))
    list3= list(df.filter(like='fee', axis=1))
    list4 = list(df.filter(like='code', axis=1))
    list5 = list(df.filter(like='status', axis=1))
    entry= list1+list2+list3+list4+list5
return entry

挑战:此代码有效,但体积庞大,我想知道是否有更好的方法来实现同样的目标

列标题示例:“ticket_id”、“agency_name”、“inspector_name”、“violator_name”、“violation_street_number”、“violation_street_name”、“violation_zip_code”、“mailing_address_str_number”、“mailing_address_str_name”、“city”、“state” '、'zip_code'、'non_us_str_code'、'country'、'ticket_issued_date'、'hearing_date'、'violation_code'、'violation_description'、'disposition'、'fine_amount'、'admin_fee'、'state_fee'、'late_fee'、 'discount_amount'、'clean_up_cost'、'judgment_amount'、'payment_amount'、'balance_due'、'payment_date'、'payment_status'、'collection_status'、'grafitti_status'、'compliance_detail'、'compliance']

【问题讨论】:

  • 您介意分享一个我们可以使用的数据框列名示例吗?
  • 用标题示例更新了我的帖子
  • 是否可以在创建DataFrame之前过滤列名?
  • 我对此没有任何限制,所以是的,有可能。

标签: python pandas dataframe filter


【解决方案1】:

您可以采取的一种方法:

#create search collection of relevant terms
search='|'.join(['fee','address','code','name'])

#use the filter method in pandas with the regex option
#then drop the 'agency_name' column
#d is the dataframe

d.filter(regex=search,axis=1).drop('agency_name',axis=1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多