簡體   English   中英

有沒有辦法刪除某些列名稱中最后一個破折號后的所有內容?

[英]Is there a way to remove everything after the last dash in certain column names?

g_20_tomato g_34_lettuce g_60_carrot price
10          24           45          11
34          47           27          77

我有以下示例 dataframe。我想刪除包含“g_”的列的最后一個連字符后的所有內容。

我試過這個:

df.rename(columns=lambda x: x.str.split('_').str[:-1].str.join('_'), inplace= True)

這給了我:AttributeError: 'str' object has no attribute 'str'

您實際上可以直接將字符串操作應用於df.columns

df.columns = df.columns.str.replace('_[^_]+$', '', regex=True)

或者:

df.columns = df.columns.str.rsplit('_', 1).str[0]

通過rename ,您可以傳遞 function 並將值評估為字符串

df.rename(lambda x: x.rsplit('_', 1)[0], axis=1)

output:

   g_20  g_34  g_60  price
0    10    24    45     11
1    34    47    27     77

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM