Select only a part of the Dataframe title

Asked

Viewed 239 times

0

Imagine the following situation, I have a Dataframe with any name. Within this Dataframe I have columns with the following titles More(abc), Less(abc), Sub(abc), following the data of each column. The name abc refers to abc data, I also have More(dfg), Less(dfg), Sub(dfg).

How do I create a function that keeps the data of each column, but when printing this data I change the column names only to abc ? That is by removing More, Less and Sub.

Thus the result would be abc plus the data and dfg plus the data, removing the More, Less, Sub and also the ().

  • I recommend you for code you already have so someone can help you.

2 answers

2

If we did this:

import pandas as pd
dicio = {"Mais(abc)":[1,2,3],"Menos(abc)":[4,5,6], "Sub(abc)":[7,8,9], 
         "Mais(dfg)":[10,11,12], "Menos(dfg)":[13,14,15], "Sub(dfg)":[16,17,18]}
df = pd.DataFrame(dicio)

The table in df will be

    Mais(abc)   Menos(abc)  Sub(abc)    Mais(dfg)   Menos(dfg)  Sub(dfg)
0   1           4           7           10          13          16
1   2           5           8           11          14          17
2   3           6           9           12          15          18

To rename the columns then do the following:

new_columns_names = ['abc', 'abc', 'abc', 'dfg', 'dfg', 'dfg']
df.columns = new_columns_names

The exit will be:

    abc         abc         abc         dfg         dfg         dfg
0   1           4           7           10          13          16
1   2           5           8           11          14          17
2   3           6           9           12          15          18

0

The best way to solve this problem is by using regex (regular expressions):

import re

df.rename(columns=lambda x: 
             re.search(r"\((.*?)\)", x).group(1) if re.search(r"\((.*?)\)", x) else x)

EDIT:

In this case the expression \((.*?)\) does the following search:

\( - Find the opening of parentheses

(.*?) - First capture group (i.e., everything within parentheses)

\) - Find the parenthesis closure

  • I loved your answer, I was really trying to use regular expressions, but I’m starting out and I still find it hard to understand.

  • Yes, it can be complicated at first. I will edit the answer to explain how this expression does the search.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.