简体   繁体   English

如何使用 Python 和 json 计算此数据集的行数?

[英]How can I count the rows of this data set using Python and json?

I am pursuing a MSc in Data Science and I have the following statement:我正在攻读数据科学硕士学位,我有以下声明:

Import the file EE_points.json from data folder.从数据文件夹导入文件 EE_points.json。 Examine the data set and display the names of the columns, the contents of the first 7 rows, and the total number of rows.检查数据集并显示列名、前 7 行的内容和总行数。

I did all the steps correctly except the last.除了最后一步,我正确地完成了所有步骤。

# My answer

import json
import pandas as pd

# To check the data set I do:

with open('./data/EE_points.json') as f:
  data = json.load(f)
  for query in data:
    print(query)

# To check the names of the columns I do:

keys = query.keys()

print(keys)

# To see the first 7 rows I do:

pd.read_json('./data/EE_points.json').head(7)

# To check the total numbers of rows I do:

length = len(query)

print(length)

The last step, when I have to count the rows printing length I get the number of columns instead of rows.最后一步,当我必须计算行打印长度时,我得到的是列数而不是行数。

There are many options depending on how the JSON is structured.根据 JSON 的结构,有很多选项。 I can't tell which would apply in your case, so I will post the 3 of them.我不知道哪个适用于您的情况,所以我将发布其中的 3 个。 Hopefully one will work for you.希望有人会为你工作。

Structured List:结构化列表:

# Count the number of rows
row_count = 0
for row in data:
    row_count += 1

print(f'Number of rows: {row_count}')

If the JSON file is a list of lists:如果 JSON 文件是列表的列表:

It's what you did, but for the data.这就是您所做的,但是是为了数据。

row_count = len(data)

If the JSON file is a dictionary and assuming that each key in the dictionary represents a row:如果 JSON 文件是字典并假设字典中的每个键代表一行:

row_count = len(data.keys())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM