Home > Blockchain >  How to remove part of a string by condition - Python->Pandas?
How to remove part of a string by condition - Python->Pandas?

Time:11-15

I have the next DataFrame:

a = [{'name': 'AAA|YYY'},{ 'name': 'BBB|LLL'}]
df = pd.DataFrame(a)
print(df)

      name
0  AAA|YYY
1  BBB|LLL

and I'm trying to remove the part of the string from the right up to the character |:

df['name'] = [i.split('|')[:-1] for i in df['name']]

but I get the following result:

    name
0  [AAA]
1  [BBB]

how can I get the following result?:

    name
0  AAA
1  BBB

CodePudding user response:

You're selecting a range of items from the result of your split operation, because you're passing a slice object (:-1).

Actually, to get your result, you just have to select the first part of the split, which will correspond to the index 0:

df['name'] = [i.split('|')[0] for i in df['name']]

Or if you have multiple occurrences of '|', and want to remove only the last part, you can join the remaining part after your selection:

df['name'] = ['|'.join(i.split('|')[:-1]) for i in df['name']]
  • Related