-1

I have dataframe column, one row contain data:

bloodtype
[{'id': 35, 
  'type': 'typeO'}]

The column contain different blood type, A,B,AB, and O in other rows.

I ran:

type(df.blood_type)

it returned 'pandas.core.series.Series'

df['blood_type'].str.split(":")[0][2]

it return " 'typeO'}]"

How can I just get typeO, typeA, typeAB so i could convert them different classes. Thanks

ernest_k
  • 39,584
  • 5
  • 45
  • 86
Ray
  • 53
  • 6
  • Possible duplicate of [Is there a way to substring a string?](https://stackoverflow.com/questions/663171/is-there-a-way-to-substring-a-string) – thepolina Feb 14 '19 at 00:13

1 Answers1

0
from ast import literal_eval
df['type'] = df['blood_type'].apply(lambda x: literal_eval(x[0]).type)

Alternate solution:

#a more robust solution to incase the series has unexpected values
def extract_type(x):
     try:
         if type(literal_eval(x)) == 'dict':
             return literal_eval(x)
         else:
             return None
     except ValueError:
         return None

df['type'] = df['blood_type'].apply(extract_type)

edit: convert string representation of dict to dictionary using ast.literal_eval before extracting type

kudeh
  • 768
  • 4
  • 14
  • Thanks but I got error: AttributeError: 'str' object has no attribute 'type' – Ray Feb 13 '19 at 18:52
  • just updated the answer to [convert](https://stackoverflow.com/questions/38694800/how-to-convert-string-into-dictionary-in-python-3/38694850) string representation of dict before extracting type. – kudeh Feb 13 '19 at 19:00