【问题标题】:add column name at the end of each value of a column pandas在列 pandas 的每个值的末尾添加列名
【发布时间】:2023-02-03 21:47:46
【问题描述】:

我有一个熊猫 df,是这样的:

     date  col1    col2    col3        col4
0  4-4-22   cat  ginger  gentle      placed
1  4-4-22   dog  golden    wild  not placed
2  4-4-22  fish   black  domest  not placed
3  4-4-22   dog   brown  gentle      placed

对于我给出的列名称列表,我希望这些列的每个值都在末尾的括号中添加列名称。例如。

lst = ['col2', 'col4']

期望的输出:

     date  col1           col2    col3               col4
0  4-4-22   cat  ginger (col2)  gentle      placed (col4)
1  4-4-22   dog  golden (col2)    wild  not placed (col4)
2  4-4-22  fish   black (col2)  domest  not placed (col4)
3  4-4-22   dog   brown (col2)  gentle      placed (col4)

【问题讨论】:

    标签: pandas


    【解决方案1】:

    我会用系列属性name

    属性 Series.name :返回系列的名称.

    lista = ["col2", "col4"]
    ​
    df[lista] = df[lista].apply(lambda x: x + f" ({x.name})")
    

    的 输出 :

    print(df)
    
         date  col1           col2    col3               col4
    0  4-4-22   cat  ginger (col2)  gentle      placed (col4)
    1  4-4-22   dog  golden (col2)    wild  not placed (col4)
    2  4-4-22  fish   black (col2)  domest  not placed (col4)
    3  4-4-22   dog   brown (col2)  gentle      placed (col4)
    

    【讨论】:

      【解决方案2】:

      在确保列是字符串后使用add(使用astype):

      cols = ['col2', 'col4']
      
      df[cols] = df[cols].astype(str).add([f' ({c})' for c in cols])
      

      输出:

           date  col1           col2    col3               col4
      0  4-4-22   cat  ginger (col2)  gentle      placed (col4)
      1  4-4-22   dog  golden (col2)    wild  not placed (col4)
      2  4-4-22  fish   black (col2)  domest  not placed (col4)
      3  4-4-22   dog   brown (col2)  gentle      placed (col4)
      

      【讨论】:

        猜你喜欢
        • 2016-07-20
        • 2023-03-21
        • 2020-10-14
        • 1970-01-01
        • 2018-02-25
        • 1970-01-01
        • 2021-11-17
        • 1970-01-01
        • 2021-01-21
        相关资源
        最近更新 更多