【问题标题】:How to unite values and column names in a new column (pandas)?如何在新列(熊猫)中统一值和列名?
【发布时间】:2018-06-06 11:08:42
【问题描述】:

给定一个可能具有可变数量的行和列的数据框 (df_original),我如何添加一列以“合并”由字符 (例如_) ?

该列的名称也应该由其他列名称的合并组成。输出应该类似于示例代码中的df_final

示例代码:

import pandas as pd
d = {'col1': ["a", "b", "c"], 'col2': ["a", "b", "c"], 'col3': ["a", "b", "c"], 'col99': ["a", "b", "c"]}
df_original = pd.DataFrame(data=d)

d2 = {'col1': ["a", "b", "c"], 'col2': ["a", "b", "c"], 'col3': ["a", "b", "c"], 'col99': ["a", "b", "c"], 'col1_col2_col3_col99' : ["a_a_a_a", "b_b_b_b", "c_c_c_c"]}
df2 = pd.DataFrame(data=d2)
cols = ["col1","col2","col3","col99","col1_col2_col3_col99"]
df_final = df2[cols]

【问题讨论】:

    标签: python python-3.x pandas dataframe string-concatenation


    【解决方案1】:

    使用pd.DataFrame.apply

    df['_'.join(df.columns)] = df.apply('_'.join, axis=1)
    
    print(df)
    
      col1 col2 col3 col99 col1_col2_col3_col99
    0    a    a    a     a              a_a_a_a
    1    b    b    b     b              b_b_b_b
    2    c    c    c     c              c_c_c_c
    

    【讨论】:

    • 以及更一般的转换为字符串列:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2021-06-25
    相关资源
    最近更新 更多