Pandas处理CSV文件的常用技巧

Pandas处理CSV文件,分为以下几步:

  1. 读取Pandas文件
  2. 统计列值出现的次数
  3. 筛选特定列值
  4. 遍历数据行
  5. 绘制直方图(柱状图📊)

读取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):

 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)

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

效果:

Pandas处理CSV文件的常用技巧

Original: https://blog.csdn.net/u012515223/article/details/125073632
Author: SpikeKing
Title: Pandas处理CSV文件的常用技巧

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/639234/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球