0

I'm new using dataframes and I don't know how to do this.

I have this dataframe (sample):

     Type                                    Count
0    http://dbpedia.org/resource/Album       21
1    http://es.dbpedia.org/resource/Book     4
2    http://es.dbpedia.org/resource/Person   7
3    http://es.dbpedia.org/resource/Film     4

I want to replace ALL the values of Type column, result will be like this (sample):

    Type      Count
0   Album     21
1   Book      4
2   Person    7
3   Film      4

Hope you can help me with this. Thanks in advance.

1 Answers1

2

You can extract the ending word (\w*$) in each string:

df['Type'] = df.Type.str.extract('(\w*)$')
df

     Type  Count
0   Album     21
1    Book      4
2  Person      7
3    Film      4

Or split and then take the last element:

df['Type'] = df.Type.str.split('/').str[-1]
df

     Type  Count
0   Album     21
1    Book      4
2  Person      7
3    Film      4
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • Not that I'm the expert. But wouldn't a better method be to replace with a matching dataframe like a vlookup ? 2 seperate corresponding matching lists, no matter the content, so the solution isn't reliant on a textual manipulation. I'm out now otherwise I would try that. – David Wooley - AST Jun 06 '21 at 18:11
  • @DavidWooley-AST I think you are talking about excel ? This is a question for pandas. – Psidom Jun 06 '21 at 18:30
  • No, I was talking more about something like [this](https://stackoverflow.com/questions/36846060/how-to-replace-an-entire-column-on-pandas-dataframe) but using excel language to explain my idea. Or something like df['Group'] = df['Type'].map(df1.set_index('Type')['Name']) from [here](https://stackoverflow.com/questions/36413993/replace-column-values-in-one-dataframe-by-values-of-another-dataframe) – David Wooley - AST Jun 06 '21 at 21:49