在列Pandas的每个值的末尾添加列名

abithluo  于 2023-02-07  发布在  其他
关注(0)|答案(2)|浏览(170)

我有一个Pandasdf,大概是这样的:

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)
wwwo4jvm

wwwo4jvm1#

在确保列是字符串之后使用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)
avkwfej4

avkwfej42#

我将使用 Series 属性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)

相关问题