- 使用
python 3.8.5
和pandas 1.1.1
当前实施
- 首先,代码读取文件并将其从 a
str
类型转换为 a dict
,json.loads
with open (file, "r") as f:
all_data = json.loads(f.read())
json.dumps(all_data['objects']['value'])
- 使用
orient='index'
将 设置keys
为列标题,并将values
设置在行中。
- 此时数据也转换为a
int
,值发生变化。
- 我猜这一步有一些浮点转换问题
pd.read_json(json.dumps(all_data['objects']['value']), orient='index')
更新代码
选项1
- 使用
pandas.DataFrame.from_dict
然后转换为数字。
file = "test_data.json"
with open (file, "r") as f:
all_data = json.loads(f.read())
# use .from_dict
data = pd.DataFrame.from_dict(all_data['objects']['value'], orient='index')
# convert columns to numeric
data[['id_1', 'id_2']] = data[['id_1', 'id_2']].apply(pd.to_numeric, errors='coerce')
data = data.reset_index(drop=True)
# display(data)
timestamp id_1 id_2
0 Wed Aug 26 08:52:57 +0000 2020 1298543947669573634 1298519559306190850
print(data.info())
[out]:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1 entries, 0 to 0
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 timestamp 1 non-null object
1 id_1 1 non-null int64
2 id_2 1 non-null int64
dtypes: int64(2), object(1)
memory usage: 152.0+ bytes
选项 2
- 使用
pandas.json_normalize
然后将列转换为数字。
file = "test_data.json"
with open (file, "r") as f:
all_data = json.loads(f.read())
# read all_data into a dataframe
df = pd.json_normalize(all_data['objects']['value'])
# rename the columns
df.columns = [x.split('.')[1] for x in df.columns]
# convert to numeric
df[['id_1', 'id_2']] = df[['id_1', 'id_2']].apply(pd.to_numeric, errors='coerce')
# display(df)
timestamp id_1 id_2
0 Wed Aug 26 08:52:57 +0000 2020 1298543947669573634 1298519559306190850
print(df.info()
[out]:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1 entries, 0 to 0
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 timestamp 1 non-null object
1 id_1 1 non-null int64
2 id_2 1 non-null int64
dtypes: int64(2), object(1)
memory usage: 152.0+ bytes