I want to convert some columns of a dataframe to json strings. I was hoping that something like the following would work but apply+json.dumps can't operate on a Series.
jcols = ['a','c']
df[jcols] = df[jcols].apply(json.dumps, axis=1).astype('string')
The following code DOES work but there must be a more straightforward way. The code uses list comprehension, Series, map(), dict to create a new dataframe containing the json string columns. What am I missing?
d = {'d':0}
df = pd.DataFrame({'a':[d,d,d],'b':[21,22,23],'c':[d,d,d]})
display(df,df.dtypes)
jcols = ['a','c']
jdf = pd.DataFrame({c:(df[c].map(json.dumps).astype('string') if c in jcols else df[c]) for c in df.columns})
display(jdf,jdf.dtypes)