Pandas 使用教程 CSV
阅读原文时间:2023年08月29日阅读:1

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')

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