数据预处理

一般例如json数据可以用Pandas进行数据处理
with open('xxx.json','r', encoding = 'utf-8') as filename

python 复制代码
import json
import pandas as pd
# 读取JSON文件, utf-8保留中文
with open('json/prompt.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
# 存储提取的内容
extracted_data = []

# 遍历
for item in data:
	if item['kwargs'] != "{}":  # 或者 if 'kwargs' in item:
		kwargs_dict = item
		extracted_data.append(kwargs_dict)

# 写入新的JSON文件,可以同时写多个,ensure_ascii false保留中文,index 缩进4格
with open('new1.json','w',encoding = 'utf-8') as newfile1, with open ('new2.json','w',encoding = 'utf-8') as newfile2:
	json.dump(extracted_data, newfile1, ensure_ascii = False, index = 4)

# df格式
df = pd.DataFrame(data)
# csv保存
# 如果需要保存为CSV文件
df.to_csv('output.csv', index=False, encoding='utf-8') # 此处index是索引,,不包含索引
		

Pandas DataFrame 提供了丰富的数据处理和查看方法。以下是一些常见的方法和示例代码:

查看数据

  1. 查看前几行数据

    python 复制代码
    df.head()

    查看前5行数据。

  2. 查看后几行数据

    python 复制代码
    df.tail()

    查看后5行数据。

  3. 查看数据的基本信息

    python 复制代码
    df.info()

    显示数据类型、非空值计数等信息。

  4. 查看描述性统计信息

    python 复制代码
    df.describe()

    显示数据的统计信息,如平均值、标准差等。

处理缺失值

  1. 查找缺失值

    python 复制代码
    df.isnull().sum()

    查看每列缺失值的数量。

  2. 删除包含缺失值的行

    python 复制代码
    df.dropna()

    删除包含任何缺失值的行。

  3. 填充缺失值

    python 复制代码
    df.fillna(value)

    用指定值填充缺失值。例如,用0填充:

    python 复制代码
    df.fillna(0)

数据选择与过滤

  1. 选择列

    python 复制代码
    df['column_name']

    选择单列数据。

    python 复制代码
    df[['column1', 'column2']]

    选择多列数据。

  2. 选择行

    使用行索引选择行:

    python 复制代码
    df.loc[0]

    使用条件过滤行:

    python 复制代码
    df[df['column_name'] > value]

数据操作

  1. 添加新列

    python 复制代码
    df['new_column'] = df['column1'] + df['column2']
  2. 删除列

    python 复制代码
    df.drop(columns=['column_name'])
  3. 重命名列

    python 复制代码
    df.rename(columns={'old_name': 'new_name'}, inplace=True)
  4. 数据排序

    python 复制代码
    df.sort_values(by='column_name', ascending=False)

数据合并

  1. 按列合并

    python 复制代码
    df1.merge(df2, on='common_column')
  2. 按行合并

    python 复制代码
    pd.concat([df1, df2])
相关推荐
Pyeako4 天前
python中pandas库的使用(超详细)
开发语言·python·pandas
ranchor6665 天前
excel+pandas使用str.contains() 的典型例子
excel·pandas
啊巴矲5 天前
小白从零开始勇闯人工智能:机器学习初级篇(pandas库)
人工智能·机器学习·pandas
Keep__Fighting5 天前
【机器学习:集成算法】
人工智能·算法·机器学习·pandas·集成学习·sklearn
Hi_kenyon5 天前
Pandas Cheatsheet I
python·pandas
万粉变现经纪人6 天前
如何解决 pip install 网络报错 403 Forbidden(访问被阻止)问题
数据库·python·pycharm·beautifulsoup·bug·pandas·pip
咚咚王者6 天前
人工智能之数据分析 Pandas:第十一章 项目实践
人工智能·数据分析·pandas
咚咚王者6 天前
人工智能之数据分析 Pandas:第十章 知识总结
人工智能·数据分析·pandas
编程设计3666 天前
pandas 中 DataFrame、mean()、groupby 和 fillna 函数的核心作用
机器学习·数据挖掘·pandas
咚咚王者6 天前
人工智能之数据分析 Pandas:第九章 性能优化
人工智能·数据分析·pandas