[英]Make dictionary from a string inside a cell of Pandas data-frame
看起來這里需要map
方法:
import re
df.loc[:, 'm'] = df['m'].map(lambda x: dict(map(lambda y: re.split(' = |: ', y), x.split('\n'))))
Output 就像:
m c x
0 {'0': 'absence', '1': 'mild', '2': 'moderate '... 1 5
1 {'0': 'no ', '1': 'yes', '2': 'Not relevant'} 1 3
2 {'1': 'smoker', '2': 'ex-smoker (not smoked)'} 1 6
如果需要密鑰作為數字,您可以添加附加行:
df.loc[:, 'm'] = df['m'].map(lambda x: {int(k): v for k, v in x.items()})
Output:
m c x
0 {0: 'absence', 1: 'mild', 2: 'moderate ', 3: '... 1 5
1 {0: 'no ', 1: 'yes', 2: 'Not relevant'} 1 3
2 {1: 'smoker', 2: 'ex-smoker (not smoked)'} 1 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.