JamesHudson81
JamesHudson81

Reputation: 2273

Removing characters index dataframe

I have the following df:

total:

                                    A       B           C         D
2   Quarter Endingds9ñs           31   25476.20   26321.00   24867.00
3   Quarter Ending dsa)d           31   26627.20   27904.00   25983.00
4      Year EndingdjAsd           34  106806.00  110738.00  103731.00
5      Year Ending (kañs           33  123813.00  131232.00  119091.00

How can I remove the last 5 characters to obtain:

total:
                             A       B           C         D
2   Quarter Ending           31   25476.20   26321.00   24867.00
3   Quarter Ending           31   26627.20   27904.00   25983.00
4      Year Ending           34  106806.00  110738.00  103731.00
5      Year Ending           33  123813.00  131232.00  119091.00

I don't really know how to clean the index deleting the last 5 characters.

Upvotes: 2

Views: 2641

Answers (3)

Axis
Axis

Reputation: 2132

If you want to clean all rows end of 5 character you can use this(could be better function)

def remove_last_chars(x):
    return (x.replace(x[-5:], ''))

after this function use that

df[df.columns[0:1]] = df[df.columns[0:1]].applymap(remove_last_chars)

Upvotes: 3

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210842

Source Multi-Index DF

In [210]: df
Out[210]:
                         A         B         C         D
2 Quarter Endingds9ñs   31   25476.2   26321.0   24867.0
3 Quarter Ending dsa)d  31   26627.2   27904.0   25983.0
4 Year EndingdjAsd      34  106806.0  110738.0  103731.0
5 Year Ending (kañs     33  123813.0  131232.0  119091.0

Solution:

In [211]: df.index.set_levels(df.index.get_level_values(1).str[:-5], level=1, inplace=True)

In [212]: df
Out[212]:
                    A         B         C         D
2 Quarter Ending   31   25476.2   26321.0   24867.0
3 Quarter Ending   31   26627.2   27904.0   25983.0
4 Year Ending      34  106806.0  110738.0  103731.0
5 Year Ending      33  123813.0  131232.0  119091.0

Upvotes: 2

Serenity
Serenity

Reputation: 36635

Use lambda function to drop last 5 symbols like:

total.index = total.index.map(lambda x: str(x)[:-5])

Upvotes: 5

Related Questions