将一些对象列转换为 json 字符串
Convert some columns of objects to json string
我想将数据框的某些列转换为 json 字符串。我希望像下面这样的东西可以工作,但是 apply+json.dumps 不能在系列上运行。
jcols = ['a','c']
df[jcols] = df[jcols].apply(json.dumps, axis=1).astype('string')
以下代码确实有效,但必须有更直接的方法。该代码使用列表推导、Series、map()、dict 创建一个包含 json 字符串列的新数据框。我错过了什么?
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)
尝试使用 applymap
代替:
df[jcols] = df[jcols].applymap(json.dumps).astype('string')
df
:
a b c
0 {"d": 0} 21 {"d": 0}
1 {"d": 0} 22 {"d": 0}
2 {"d": 0} 23 {"d": 0}
df.dtypes
:
a string
b int64
c string
dtype: object
完整的工作示例:
import pandas as pd
import json
d = {'d': 0}
df = pd.DataFrame({'a': [d, d, d], 'b': [21, 22, 23], 'c': [d, d, d]})
jcols = ['a', 'c']
df[jcols] = df[jcols].applymap(json.dumps).astype('string')
print(df)
print(df.dtypes)
我觉得可以很简单:
>>> df = pd.DataFrame({'a':[d,d,d],'b':[21,22,23],'c':[d,d,d]})
>>> df
a b c
0 {'d': 0} 21 {'d': 0}
1 {'d': 0} 22 {'d': 0}
2 {'d': 0} 23 {'d': 0}
>>> df.dtypes
a object
b int64
c object
不导入json
就可以:
>>> df[jcols] = df[jcols].astype('string')
>>> df.dtypes
a string
b int64
c string
dtype: object
如果要更改的列有限,甚至更简单:
>>> df.astype({'a': 'string', 'c': 'string'}).dtypes
a string
b int64
c string
dtype: object
我想将数据框的某些列转换为 json 字符串。我希望像下面这样的东西可以工作,但是 apply+json.dumps 不能在系列上运行。
jcols = ['a','c']
df[jcols] = df[jcols].apply(json.dumps, axis=1).astype('string')
以下代码确实有效,但必须有更直接的方法。该代码使用列表推导、Series、map()、dict 创建一个包含 json 字符串列的新数据框。我错过了什么?
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)
尝试使用 applymap
代替:
df[jcols] = df[jcols].applymap(json.dumps).astype('string')
df
:
a b c
0 {"d": 0} 21 {"d": 0}
1 {"d": 0} 22 {"d": 0}
2 {"d": 0} 23 {"d": 0}
df.dtypes
:
a string
b int64
c string
dtype: object
完整的工作示例:
import pandas as pd
import json
d = {'d': 0}
df = pd.DataFrame({'a': [d, d, d], 'b': [21, 22, 23], 'c': [d, d, d]})
jcols = ['a', 'c']
df[jcols] = df[jcols].applymap(json.dumps).astype('string')
print(df)
print(df.dtypes)
我觉得可以很简单:
>>> df = pd.DataFrame({'a':[d,d,d],'b':[21,22,23],'c':[d,d,d]})
>>> df
a b c
0 {'d': 0} 21 {'d': 0}
1 {'d': 0} 22 {'d': 0}
2 {'d': 0} 23 {'d': 0}
>>> df.dtypes
a object
b int64
c object
不导入json
就可以:
>>> df[jcols] = df[jcols].astype('string')
>>> df.dtypes
a string
b int64
c string
dtype: object
如果要更改的列有限,甚至更简单:
>>> df.astype({'a': 'string', 'c': 'string'}).dtypes
a string
b int64
c string
dtype: object