![](/img/trans.png)
[英]How to remove everything (except certain characters) after the last number in a string
[英]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.