【问题标题】:How to replace a list of longer column names with small names in a dataset?如何用数据集中的小名称替换较长的列名称列表?
【发布时间】:2019-12-07 04:48:47
【问题描述】:
  • 我有一个列名列表,这些列名太长以至于会弄乱代码。我想用一个较短的列表名称替换该列名称列表。
  • 以下是列示例:
    non_multi_choice = ["what_is_the_highest_level_of_formal_education_that_you_have_attained_or_plan_to_attain_within_the_next_2_years",
          "select_the_title_most_similar_to_your_current_role_or_most_recent_title_if_retired_selected_choice",
          "in_what_industry_is_your_current_employer_contract_or_your_most_recent_employer_if_retired_selected_choice",
          "how_many_years_of_experience_do_you_have_in_your_current_role",
          "what_is_your_current_yearly_compensation_approximate_usd",
          "does_your_current_employer_incorporate_machine_learning_methods_into_their_business",
          "of_the_choices_that_you_selected_in_the_previous_question_which_ml_library_have_you_used_the_most_selected_choice",
          "approximately_what_percent_of_your_time_at_work_or_school_is_spent_actively_coding"]
    shorter_names = ["highest_level_of_formal_education",
      "job_title",
      "current_industry",
      "years_of_experience",
      "yearly_compensation",
      "does_your_current_employer_incorporate_machine_learning_methods_into_their_business",
      "which_ml_library_have_you_used_the_most_selected_choice",
      "what_percent_of_your_time_at_work_is_spent_actively_coding"]
  • 我想将第一个列表中的每个名称替换为第二个列表中与之对应的名称。

【问题讨论】:

  • 这没有多大意义。为什么不直接使用shorter_names?或者,如果必须,复制 reference non_multi_choice = shorter_names

标签: python python-3.x data-science data-analysis


【解决方案1】:

这样的事情怎么样:

for index, item in enumerate(non_multi_choice):
  non_multi_choice[index] = shorter_names[index]

【讨论】:

    【解决方案2】:

    如果这些包含所有列名,则:

    df.columns = shorter_names
    

    如果没有

    df.rename(columns = {old:new for old, new in zip(non_multi_choice, shorter_names})
    

    【讨论】:

      猜你喜欢
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 2022-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多