Python Pandas处理CSV文件的常用技巧分享
作者:SpikeKing 发布时间:2022-06-18 12:56:19
Pandas处理CSV文件,分为以下几步:
读取Pandas文件
统计列值出现的次数
筛选特定列值
遍历数据行
绘制直方图(柱状图)
读取Pandas文件
df = pd.read_csv(file_path, encoding='GB2312')
print(df.info())
注意:Pandas的读取格式默认是UTF-8,在中文CSV中会报错:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd1 in position 2: invalid continuation byte
修改编码为 GB2312 ,即可,或者忽略encode转义错误,如下:
df = pd.read_csv(file_path, encoding='GB2312')
df = pd.read_csv(file_path, encoding='unicode_escape')
df.info()显示df的基本信息,例如:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3840 entries, 0 to 3839
Data columns (total 16 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 实验时间批次 3840 non-null object
1 物镜倍数 3840 non-null object
2 板子编号 3840 non-null object
3 板子编号及物镜倍数 3840 non-null object
4 图名称 3840 non-null object
5 细胞类型 3840 non-null object
6 板子孔位置 3840 non-null object
7 孔拍摄位置 3840 non-null int64
8 细胞培养基 3840 non-null object
9 细胞培养时间(小时) 3840 non-null int64
10 扰动类别 3840 non-null object
11 扰动处理时间(小时) 3840 non-null int64
12 扰动处理浓度(ug/ml) 3840 non-null float64
13 标注激活(1/0) 3840 non-null int64
14 unique 3840 non-null object
15 tvt 3840 non-null int64
dtypes: float64(1), int64(5), object(10)
memory usage: 480.1+ KB
统计列值出现的次数
df[列名].value_counts()
,如df["扰动类别"].value_counts():
df["扰动类别"].value_counts()
输出:
coated OKT3 720
OKT3 720
coated OKT3+anti-CD28 576
DMSO 336
anti-CD28 288
PBS 288
Nivo 288
Pemb 288
empty 192
coated OKT3 + anti-CD28 144
Name: 扰动类别, dtype: int64
直接绘制value_counts()的柱形图,参考Pandas - Chart Visualization:
import matplotlib.pyplot as plt
%matplotlib inline
plt.close("all")
plt.figure(figsize=(20, 8))
df["扰动类别"].value_counts().plot(kind="bar")
# plt.xticks(rotation='vertical', fontsize=10)
plt.show()
柱形图:
筛选特定列值
df.loc[筛选条件]
,筛选特定列值之后,重新赋值,只处理筛选值,也可以写入csv文件。
df_plate1 = df.loc[df["板子编号"] == "plate1"]
df_plate1.info()
# df.loc[df["板子编号"] == "plate1"].to_csv("batch3_IOStrain_klasses_utf8_plate1.csv") # 存储CSV文件
注意:筛选的内外两个df需要相同,否则报错
pandas loc IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).
输出,数据量由3840下降为1280。
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1280 entries, 0 to 1279
Data columns (total 16 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 实验时间批次 1280 non-null object
1 物镜倍数 1280 non-null object
2 板子编号 1280 non-null object
3 板子编号及物镜倍数 1280 non-null object
4 图名称 1280 non-null object
5 细胞类型 1280 non-null object
6 板子孔位置 1280 non-null object
7 孔拍摄位置 1280 non-null int64
8 细胞培养基 1280 non-null object
9 细胞培养时间(小时) 1280 non-null int64
10 扰动类别 1280 non-null object
11 扰动处理时间(小时) 1280 non-null int64
12 扰动处理浓度(ug/ml) 1280 non-null float64
13 标注激活(1/0) 1280 non-null int64
14 unique 1280 non-null object
15 tvt 1280 non-null int64
dtypes: float64(1), int64(5), object(10)
memory usage: 170.0+ KB
遍历数据行
for idx, row in df_plate1_lb0.iterrows():
,通过row[“列名”],输出具体的值,如下:
for idx, row in df_plate1_lb0.iterrows():
img_name = row["图名称"]
img_ch_format = img_format.format(img_name, "{}")
for i in range(1, 7):
img_path = os.path.join(plate1_img_folder, img_ch_format.format(i))
img = cv2.imread(img_path)
print('[Info] img shape: {}'.format(img.shape))
break
输出:
[Info] img shape: (1080, 1080, 3)
[Info] img shape: (1080, 1080, 3)
[Info] img shape: (1080, 1080, 3)
[Info] img shape: (1080, 1080, 3)
[Info] img shape: (1080, 1080, 3)
[Info] img shape: (1080, 1080, 3)
绘制直方图(柱状图)
统计去除背景颜色的灰度图字典
# 去除背景颜色
pix_bkg = np.argmax(np.bincount(img_gray.ravel()))
img_gray = np.where(img_gray <= pix_bkg + 2, 0, img_gray)
img_gray = img_gray.astype(np.uint8)
# 生成数值数组
hist = cv2.calcHist([img_gray], [0], None, [256], [0, 256])
hist = hist.ravel()
# 数值字典
hist_dict = collections.defaultdict(int)
for i, v in enumerate(hist):
hist_dict[i] += int(v)
# 去除背景颜色,已经都统计到0,所以0值非常大,删除0值,观察分布
hist_dict[0] = 0
绘制柱状图:
plt.subplots:设置多个子图,figsize背景尺寸,facecolor背景颜色
ax.set_title:设置标题
ax.bar:x轴的值,y轴的值
ax.set_xticks:x轴的显示间隔
plt.savefig:存储图像
plt.show:展示
fig, ax = plt.subplots(1, 1, figsize=(10, 8), facecolor='white')
ax.set_title('channel {}'.format(ci))
n_bins = 100
ax.bar(range(n_bins+1), [hist_dict.get(xtick, 0) for xtick in range(n_bins+1)])
ax.set_xticks(range(0, n_bins, 5))
plt.savefig(res_path)
plt.show()
效果:
来源:https://blog.csdn.net/caroline_wendy/article/details/125073632


猜你喜欢
- 这是经常用的一个分页存储过程 希望大家指点不足 代码如下:USE [a6756475746] GO /****** Object
- 大家好,我是东哥。本篇和大家介绍一个经典的异常检测算法:局部离群因子(Local Outlier Factor),简称LOF算法。背景Loc
- 学习任何一门语言都是从入门(1年左右),通过不间断练习达到熟练水准(3到5年),少数人最终能精通语言,成为执牛耳者,他们是金字塔的最顶层。虽
- zip文件是我们经常使用的打包格式之一,python解压和压缩zip效率非凡。 python解压zip文档:#/usr/bin/python
- Python的装饰器(decorator)是一个很棒的机制,也是熟练运用Python的必杀技之一。装饰器,顾名思义,就是用来装饰的,它装饰的
- 如下所示:list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] slice = random.sample(list
- 你可能会遇到这样的要求,一个脚本,只允许有一个实例。在python中,为了实现这个需求,可以引入fcntl模块对文件加一个排他锁,这样一来,
- 在安装pip前,请确认win系统中已经安装好了python,和easy_install工具,如果系统安装成功,easy_install在目录
- Go语言提供了一个内置函数 delete(),用于删除容器内的元素,下面我们简单介绍一下如何用 delete() 函数删除 map 内的元素
- 导入相关包import timeimport pydashimport base64import requestsfrom lxml imp
- 这两天看了下某位大神的github,知道他对算法比较感兴趣,看了其中的一个计算数字的步数算法,感觉这个有点意思,所以就自己实现了一个。算法描
- 一、前言刚开始学Python的小伙伴可能会觉得每次写Python打开Cmd或者idle有点烦躁,没有代码补全也没有格式提示等。所以直接上手了
- 不管是业务数据分析 ,还是数据建模。数据处理都是及其重要的一个步骤,它对于最终的结果来说,至关重要。今天,就为大家总结一下 “Pandas数
- 1.基本介绍在OpenCV中,图像通道是按照 B 通道→G 通道→R 通道的顺序存储的。在图像处理过程中,可以根据需要对通道进行拆分和合并。
- Qt Designer用于像VC++的MFC一样拖放、设计控件PyUIC用于将Qt Designer生成的.ui文件转换成.py文件Qt D
- 阅读上一篇:AJAX的jQuery实现入门(一)要写入数据库,我们知道的最简单的就是注册了, 就做个最简单的注册表单, 看看是如何提交数据的
- 进行访问MySQL数据库的方法有很多种,下面将向大家介绍一些很简单实用的用的方法和示例与大家一起分享。方法一:使用MYSQL推出的MySQL
- vue在data中定义图片相对路径:data() { return { active: 1, ico
- 效果图:代码如下:<!DOCTYPE html><html><head> <meta charse
- 总是记不住API。昨晚写的时候用到了这些,但是没记住,于是就索性整理一下吧:python中对文件、文件夹(文件操作函数)的操作需要涉及到os