步骤:
- 统计每一个列的标签个数
- 去除或者填充某一列NaN值
- 遍历某一列
- 分组统计
- 在DataFrame中插入行
- 在DataFrame中追加行
pandas读取Json数据或csv数据
以一个json数据为例,只要json每一个object都一致就可以:
# 读取json或csv
df_f = pd.read_json(ROOT + 'metadata_compiled.csv')
df_f = pd.read_csv(ROOT+'metadata_compiled.csv', header=0, index_col=0)
# 保存csv
new_df.to_csv("./newframe.csv", sep=',')
groupby+count统计、去除或填充NaN
import os
import numpy as np
import pandas as pd
from tqdm import tqdm
import soundfile
root_path = "F:/DATAS/***/***-main/"
metafilename = "metadata.json"df_f = pd.read_json(root_path + metafilename)
print(df_f.head(10))# 统计一些列的值的数目,用groupby+count
print("--> shape:", df_f.shape) # 1324 7
print(df_f.groupby("B")["filename"].count()) # sum to 1120
print(df_f.groupby("C")["filename"].count()) # sum to 674
print(df_f.groupby("D")["filename"].count()) # sum to 1324
print(df_f.groupby("E")["filename"].count()) # sum to 1324
print(df_f.groupby("F")["filename"].count()) # sum to 204# 填充A列的NaN
# df_f["A"] = df_f["A"].fillna(2)
# 去除B列的NaN
# df_f = df_f.dropna(subset=["B"])
遍历DataFramem
pandas DataFrame的遍历
有多种方法,介绍一种
用itertuples得到迭代体,用getattr获取列值。
dura_list = []# for idx, row in tqdm(enumerate(df_f.iterrows()), total=len(df_f)):
for idx, row in tqdm(enumerate(df_f.itertuples()), total=len(df_f)):# print(idx, row)fname = root_path + "raw/" +getattr(row, "filename")try:samples, sample_rate = soundfile.read(fname, dtype='float32')except Exception as e:print(e)print(fname)duration = samples.shape[0] / float(sample_rate)dura_list.append(duration)
print(dura_list)
列表画直方图
统计所得列表的直方图,参考菜鸟教程
import matplotlib.pyplot as plt
plt.hist(cnt, bins=30, color='skyblue', alpha=0.8)# 设置图表属性
plt.title('RUNOOB hist() Test')
plt.xlabel('Value')
plt.ylabel('Frequency')# 显示图表
plt.show()
也可以用seaborn库的displot或countplot直接画出更好看的图。
插入数据
pandas DataFrame并没有提供插入一行数据的方法,可能是因为会打乱索引吧,一种方法是,先插入一个索引,然后插入一行数据,然后重新设置索引:
# reference:https://blog.csdn.net/sunmingyang1987/article/details/105486710
def insert_addidx(df, row, idx):df = df.reindex(index=df.index.insert(idx, str(idx)))df.loc[str(idx)] = rowdf.reset_index(drop=True)return df
这里的df是DataFrame,row是df.iloc[[rownum], :]或者df.loc[index]所得的一行DataFrame,idx是int值表示行索引。
需注意获取一行数据的方式是:df.iloc[[idx], :],而不是df.iloc[idx, :]。
追加数据
追加数据其实可以用:
df.append(row)的方式,但是会报warning,官方建议的方法是:
new_df = pd.concat([new_df, df.iloc[[idx], :]], axis=0)
需注意获取一行数据的方式是:df.iloc[[idx], :],而不是df.iloc[idx, :],也意味着可以一次追加多个列。
。