How to apply a ribbon to a dataframe based on the last characters of each label?

Asked

Viewed 35 times

2

I need to apply a line filter to a dataframe based on the last characters of a label, if it contains BRL after the hyphen. Ex.: BTC-BRL. Can someone help me?

  • Current data:

    inserir a descrição da imagem aqui

  • Data after applying filter:

    inserir a descrição da imagem aqui

2 answers

2


One solution is to create a filter using list comprehension:

filtro=[k[-3:]=='BRL' for k in df.A]

df=df[filtro]

Example with fictitious database:

import pandas as pd
import random

df=pd.DataFrame({"A":["BTC-BRL", "ETH-USD","WAVES-USD","ADA-BRL"]*5, "B":[random.choice(range(5)) for k in range(20)]})

print(df)

Bench before:

            A  B
0     BTC-BRL  3
1     ETH-USD  1
2   WAVES-USD  2
3     ADA-BRL  1
4     BTC-BRL  3
5     ETH-USD  2
6   WAVES-USD  2
7     ADA-BRL  0
8     BTC-BRL  4
9     ETH-USD  0
10  WAVES-USD  4
11    ADA-BRL  0
12    BTC-BRL  4
13    ETH-USD  1
14  WAVES-USD  0
15    ADA-BRL  4
16    BTC-BRL  1
17    ETH-USD  1
18  WAVES-USD  4
19    ADA-BRL  1

Applying the filter:

filtro=[k[-3:]=='BRL' for k in df.A] 
df=df[filtro]
print(df)

Returns:

          A  B
0   BTC-BRL  3
3   ADA-BRL  1
4   BTC-BRL  3
7   ADA-BRL  0
8   BTC-BRL  4
11  ADA-BRL  0
12  BTC-BRL  4
15  ADA-BRL  4
16  BTC-BRL  1
19  ADA-BRL  1
  • It was exactly this solution that I was looking for. Thank you very much.

2

A solution similar to Lucas' would be to use the apply lambda

df[df['A'].apply(lambda x: x[-3:] == 'BRL')]

You could also use split

df[df['A'].str.split('-').apply(lambda x: x[1] == 'BRL')]

In both cases the output is:

          A     B
0   BTC-BRL     2
3   ADA-BRL     1
4   BTC-BRL     2
7   ADA-BRL     4
8   BTC-BRL     1
11  ADA-BRL     3
12  BTC-BRL     0
15  ADA-BRL     1
16  BTC-BRL     4
19  ADA-BRL     0

Browser other questions tagged

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