Pandas JSON到CSV替换值问题

x8diyxa7  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(62)

我是Python的新手,无法找到我的问题的答案(虽然我可能用词错误)。
将JSON文件转换为CSV文件。其中一个列值为**[999-999-9999]**的文件,但我需要删除两端的方括号。我研究了一下,发现我可以使用re.sub,但是必须在我的数据集上使用str(),因为如果不使用str(),数据将保留括号。但是,现在它不会再将输出文件保存到csv。有人能告诉我正确的方向吗?
x1c 0d1x的数据

import pandas as pd
import json
import re

with open(r'C:\Users\RKM\Documents\json_file.json') as f:
    data = json.load(f)

df = pd.json_normalize(data, record_path =['value'])
df_clean = re.sub(r"[\([{})\]]", "", str(df))
df_clean.to_csv(r'C:\Users\RKM\Documents\output_file.csv', index=False, na_rep="NULL")

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[146], line 10
      8 df = pd.json_normalize(data, record_path =['value'])
      9 df_clean = re.sub(r"[\([{})\]]", "", str(df))
---> 10 df_clean.to_csv(r'C:\Users\RKM\Documents\output_file.csv', index=False, na_rep="NULL")

AttributeError: 'str' object has no attribute 'to_csv'

字符串
我尝试不使用str(dt)而只使用dt,但它无法从输出csv文件中删除方括号。我希望它被删除,所以尝试了str(dt),但现在它给了我'str'对象没有属性'to_csv'的错误。

**编辑以添加:**我将代码更新到下面。我treid pd.DataFrame和.to_frame(),但它说:ValueError:未正确调用DataFrame构造函数!

import pandas as pd
import json
import re

with open(r'C:\Users\RKM\Documents\json_file.json') as f:
    data = json.load(f)

base_df = pd.json_normalize(data, record_path =['value'])
base_df_clean = re.sub(r"[\([{})\]]", "", str(df))

#df = base_df_clean.to_frame()
df = pd.DataFrame(base_df_clean)
print(df)
df_clean.to_csv(r'C:\Users\RKM\Documents\output_file.csv', index=False, na_rep="NULL")

wfauudbj

wfauudbj1#

基于没有给出样本数据的假设,您可以使用.explode():

import pandas as pd

data = {
    "businessPhones": [["999-999-9999"], ["111-111-1111"]],
    "displayName": ["user1234", "user4567"],
    "givenName": ["joe", "mike"]
}
base_df = pd.DataFrame(data=data).explode("businessPhones")
print(base_df)

字符串
输出量:

businessPhones displayName givenName
0   999-999-9999    user1234       joe
1   111-111-1111    user4567      mike

相关问题