Pandas 使用教程 CSV - CSV 转 JSON

简介: Pandas 使用教程 CSV - CSV 转 JSON

目录


CSV(Comma-Separated Values,逗号分隔值,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。

CSV 是一种通用的、相对简单的文件格式,被用户、商业和科学广泛应用。

AttributeError: partially initialized module 'pandas' has no attribute 'read_csv' (most likely due to a circular import)

``

升级 Pandas

pip install --upgrade pandas -i https://pypi.tuna.tsinghua.edu.cn/simple

如果代码点进去,能看到有 read_csv 方法 ,但还报不存在,检查一下文件名,开始我使用的是 csv.py 估计是冲突了

demo.json

[
    {
        "name":"张三",
        "age":23,
        "gender":true
    },
    {
        "name":"李四",
        "age":24,
        "gender":true
    },
    {
        "name":"王五",
        "age":25,
        "gender":false
    }
]

JSON 转换为 CSV

非常方便,只要通过 pd.read_json 读出JSON数据,再通过 df.to_csv 写入 CSV 即可

import pandas as pd
json_path = 'data/demo.json'
# 加载 JSON 数据
with open(json_path, 'r', encoding='utf8') as f:
    # 解析一个有效的JSON字符串并将其转换为Python字典
    df = pd.read_json(f.read())
    print(df.to_string())  # to_string() 用于返回 DataFrame 类型的数据,我们也可以直接处理 JSON 字符串。
    print('-' * 10)
    # 重新定义标题
    df.columns = ['姓名', '年龄', '性别']
    print(df)
    df.to_csv('data/result.csv', index=False, encoding='GB2312')

CSV 转 JSON

import csv
import json
# 读取CSV文件
with open('data/result.csv', 'r', encoding='utf-8') as csv_file:
    # csv.DictReader创建一个CSV读取器,它将读取到的数据转换为列表。
    csv_reader = csv.DictReader(csv_file)
    data = [row for row in csv_reader]
# 将数据转换为JSON格式,
"""
ensure_ascii 中文直接显示
indent=4 格式化,参数则使生成的JSON格式更美观。
"""
json_data = json.dumps(data, ensure_ascii=False, indent=4)
print(json_data)
# 将JSON数据写入文件
with open('data/output.json', 'w', encoding='utf-8') as json_file:
    json_file.write(json_data)

行、列操作

import pandas as pd
df = pd.read_csv('data/result.csv', encoding='GB2312')
print(df.to_string())  # 如果不使用该函数,则输出结果为数据的前面 5 行和末尾 5 行,中间部分以 ... 代替。
print(('-' * 10) + " 取前 N 行")
# head( n ) 方法用于读取前面的 n 行,如果不填参数 n ,默认返回 5 行。
print(df.head(1))
print(('-' * 10) + " 取尾部 N 行")
# tail( n ) 方法用于读取尾部的 n 行,如果不填参数 n ,默认返回 5 行,空行各个字段的值返回 NaN。
print(df.tail(2))
print(('-' * 10) + " info() 方法返回表格的一些基本信息:")
# info() 方法返回表格的一些基本信息:
print(df.info())

结果输出:

姓名  年龄     性别
0  张三  23   True
1  李四  24   True
2  王五  25  False
---------- 取前 N 行
   姓名  年龄    性别
0  张三  23  True
---------- 取尾部 N 行
   姓名  年龄     性别
1  李四  24   True
2  王五  25  False
---------- info() 方法返回表格的一些基本信息:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   姓名      3 non-null      object
 1   年龄      3 non-null      int64 
 2   性别      3 non-null      bool  
dtypes: bool(1), int64(1), object(1)
memory usage: 179.0+ bytes
None

目录
相关文章
|
3月前
|
XML JSON JavaScript
Pandas JSON
10月更文挑战第27天
38 0
|
3月前
|
SQL 数据采集 数据挖掘
Pandas 教程
10月更文挑战第25天
82 2
|
4月前
|
SQL 分布式计算 Java
大数据-96 Spark 集群 SparkSQL Scala编写SQL操作SparkSQL的数据源:JSON、CSV、JDBC、Hive
大数据-96 Spark 集群 SparkSQL Scala编写SQL操作SparkSQL的数据源:JSON、CSV、JDBC、Hive
107 0
|
4月前
|
存储 JSON 数据格式
Python 输入输出与文件处理: io、pickle、json、csv、os.path 模块详解
Python 输入输出与文件处理: io、pickle、json、csv、os.path 模块详解
60 0
|
5月前
|
数据采集 数据挖掘 数据处理
使用Python和Pandas处理CSV数据
使用Python和Pandas处理CSV数据
162 5
|
6月前
|
JSON 数据格式 Python
Pandas 使用教程 JSON
Pandas 使用教程 JSON
59 0
|
6月前
|
SQL 数据采集 JSON
Pandas 使用教程 Series、DataFrame
Pandas 使用教程 Series、DataFrame
94 0
|
6月前
|
存储 数据采集 JSON
CSV 和 JSON
【8月更文挑战第15天】
42 3
|
6月前
|
存储 数据采集 JSON
数据存储的正确规范:csv/xlsx和JSON全方位解析
数据存储的正确规范:csv/xlsx和JSON全方位解析
86 1
|
7月前
|
存储 JSON 数据格式
Python教程:json中load和loads的区别
【7月更文挑战第17天】在Python的`json`模块中, `load`与`loads`函数均用于JSON至Python对象的转换, 区别在于: - **`loads`**处理JSON格式的**字符串** 其中`data.json`文件内容为`{&quot;name&quot;: &quot;Bob&quot;, &quot;age&quot;: 30}`。 简而言之, `loads`用于字符串, 而`load`用于文件对象。根据数据来源选择合适的方法。
163 5