Son*_*nya 7 python json pandas
我有 pandas df 和 column metadata。此列包含嵌套字典。我想去掉每行中值周围的单引号。json.loads(data)仅使用我传递的一个值就可以正常工作。
下面的例子:
data = '{"dek": "<p>Don\'t forget to buy a card</p>", "links": {"edit": {"dev": "...}}}'
data_json = json.loads(data)
data
Run Code Online (Sandbox Code Playgroud)
输出:
{"dek": "<p>Don\'t forget to buy a card</p>", "links": {"edit": {"dev": "...}}}
然而,当我尝试将其实现到metadata列中的每一行时,它给了我一个错误。这是代码:
for index, row in sample_df.iterrows():
sample_df['metadata'] = json.loads(sample_df["metadata"])
Run Code Online (Sandbox Code Playgroud)
TypeError: the JSON object must be str, bytes or bytearray, not Series
数据集示例:
id metadata title
123 {"dek": "<p>Student loan debt is crippling a g... channel
124 {"dek": "<p>Student loan debt is crippling a... fashion
Run Code Online (Sandbox Code Playgroud)
小智 8
尝试使用以下代码:
sample_df['metadata'] = sample_df['metadata'].apply(json.loads)
Run Code Online (Sandbox Code Playgroud)
Panda 的 apply 函数,将该函数传递给该系列的每个值。它非常有用,因为您可以跳过每一行的迭代。如果您想了解有关此功能以及可以更改的参数的更多信息,请参阅此处的官方文档。
| 归档时间: |
|
| 查看次数: |
10755 次 |
| 最近记录: |