Pythonライブラリのjsonはjson文字列をdictに変換できる一方で、若干癖がある。
以下だとjson.loadsでdictに変換される。
sample= json.loads('{"sample1":"a","sample2":"b"}')

しかし、シングルクォートとダブルクォートを入れ替えると変換できない。
sample2= json.loads("{'sample1':'a','sample2':'b'}")
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

解決方法
シンプルにreplaceで置換するとよい。
sample3= json.loads("{'sample1':'a','sample2':'b'}".replace("\'",'\"'))

DataFrameの場合applyで展開する。
import pandas as pd
#make data
sample_data={"sample":["a","b","c"]}
sample_df=pd.DataFrame(sample_data)
sample_df["sample_str"] = "{'sample1':'a','sample2':'b'}"
#str to dict
sample_df["sample_dict"] = sample_df["sample_str"].apply(lambda x: json.loads(x.replace("\'", '\"')))

コメント