欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python Pandas處理CSV文件的常用技巧分享

 更新時間:2022年06月08日 11:31:54   作者:SpikeKing  
這篇文章主要和大家分享幾個Python Pandas中處理CSV文件的常用技巧,如:統(tǒng)計(jì)列值出現(xiàn)的次數(shù)、篩選特定列值、遍歷數(shù)據(jù)行等,需要的可以參考一下

Pandas處理CSV文件,分為以下幾步:

  • 讀取Pandas文件
  • 統(tǒng)計(jì)列值出現(xiàn)的次數(shù)
  • 篩選特定列值
  • 遍歷數(shù)據(jù)行
  • 繪制直方圖(柱狀圖)

讀取Pandas文件

df = pd.read_csv(file_path, encoding='GB2312')
print(df.info())

注意:Pandas的讀取格式默認(rèn)是UTF-8,在中文CSV中會報(bào)錯:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd1 in position 2: invalid continuation byte

修改編碼為 GB2312 ,即可,或者忽略encode轉(zhuǎn)義錯誤,如下:

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   實(shí)驗(yàn)時間批次         3840 non-null   object 
 1   物鏡倍數(shù)           3840 non-null   object 
 2   板子編號           3840 non-null   object 
 3   板子編號及物鏡倍數(shù)      3840 non-null   object 
 4   圖名稱            3840 non-null   object 
 5   細(xì)胞類型           3840 non-null   object 
 6   板子孔位置          3840 non-null   object 
 7   孔拍攝位置          3840 non-null   int64  
 8   細(xì)胞培養(yǎng)基          3840 non-null   object 
 9   細(xì)胞培養(yǎng)時間(小時)     3840 non-null   int64  
 10  擾動類別           3840 non-null   object 
 11  擾動處理時間(小時)     3840 non-null   int64  
 12  擾動處理濃度(ug/ml)  3840 non-null   float64
 13  標(biāo)注激活(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

統(tǒng)計(jì)列值出現(xiàn)的次數(shù)

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文件

注意:篩選的內(nèi)外兩個df需要相同,否則報(bào)錯

pandas loc IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).

輸出,數(shù)據(jù)量由3840下降為1280。

<class 'pandas.core.frame.DataFrame'>
Int64Index: 1280 entries, 0 to 1279
Data columns (total 16 columns):
 #   Column         Non-Null Count  Dtype  
---  ------         --------------  -----  
 0   實(shí)驗(yàn)時間批次         1280 non-null   object 
 1   物鏡倍數(shù)           1280 non-null   object 
 2   板子編號           1280 non-null   object 
 3   板子編號及物鏡倍數(shù)      1280 non-null   object 
 4   圖名稱            1280 non-null   object 
 5   細(xì)胞類型           1280 non-null   object 
 6   板子孔位置          1280 non-null   object 
 7   孔拍攝位置          1280 non-null   int64  
 8   細(xì)胞培養(yǎng)基          1280 non-null   object 
 9   細(xì)胞培養(yǎng)時間(小時)     1280 non-null   int64  
 10  擾動類別           1280 non-null   object 
 11  擾動處理時間(小時)     1280 non-null   int64  
 12  擾動處理濃度(ug/ml)  1280 non-null   float64
 13  標(biāo)注激活(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

遍歷數(shù)據(jù)行

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)

繪制直方圖(柱狀圖)

統(tǒng)計(jì)去除背景顏色的灰度圖字典

# 去除背景顏色
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)

# 生成數(shù)值數(shù)組
hist = cv2.calcHist([img_gray], [0], None, [256], [0, 256]) 
hist = hist.ravel()

# 數(shù)值字典
hist_dict = collections.defaultdict(int)
for i, v in enumerate(hist):
    hist_dict[i] += int(v)

# 去除背景顏色,已經(jīng)都統(tǒng)計(jì)到0,所以0值非常大,刪除0值,觀察分布
hist_dict[0] = 0

繪制柱狀圖:

  • plt.subplots:設(shè)置多個子圖,figsize背景尺寸,facecolor背景顏色
  • ax.set_title:設(shè)置標(biāo)題
  • 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()

效果:

到此這篇關(guān)于Python Pandas處理CSV文件的常用技巧分享的文章就介紹到這了,更多相關(guān)Pandas處理CSV文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python將類似json的數(shù)據(jù)存儲到MySQL中的實(shí)例

    python將類似json的數(shù)據(jù)存儲到MySQL中的實(shí)例

    今天小編就為大家分享一篇python將類似json的數(shù)據(jù)存儲到MySQL中的實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • 詳解Python3注釋知識點(diǎn)

    詳解Python3注釋知識點(diǎn)

    在本篇文章里小編給大家分享了關(guān)于Python3注釋的相關(guān)知識點(diǎn)以及用法,需要的朋友們學(xué)習(xí)下。
    2019-02-02
  • python操作excel文件并輸出txt文件的實(shí)例

    python操作excel文件并輸出txt文件的實(shí)例

    今天小編就為大家分享一篇python操作excel文件并輸出txt文件的實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • Python函數(shù)關(guān)鍵字參數(shù)及用法詳解

    Python函數(shù)關(guān)鍵字參數(shù)及用法詳解

    本文主要介紹了Python函數(shù)關(guān)鍵字參數(shù)及用法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • 20非常有用的Python單行代碼分享

    20非常有用的Python單行代碼分享

    有用的 Python 單行代碼片段,只需一行代碼即可解決特定編碼問題!本文將分享20 個 Python 一行代碼,你可以在 30 秒或更短的時間內(nèi)輕松學(xué)習(xí)它們。這種單行代碼將節(jié)省你的時間,并使你的代碼看起來更干凈且易于閱讀
    2022-11-11
  • Python生成數(shù)字圖片代碼分享

    Python生成數(shù)字圖片代碼分享

    這篇文章主要介紹了Python生成數(shù)字圖片代碼分享,具有一定參考價值,需要的朋友可以了解下。
    2017-10-10
  • Python中實(shí)例化class的執(zhí)行順序示例詳解

    Python中實(shí)例化class的執(zhí)行順序示例詳解

    這篇文章主要給大家介紹了關(guān)于Python中實(shí)例化class的執(zhí)行順序的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價值,需要的朋友們隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-10-10
  • TensorFlow卷積神經(jīng)網(wǎng)絡(luò)AlexNet實(shí)現(xiàn)示例詳解

    TensorFlow卷積神經(jīng)網(wǎng)絡(luò)AlexNet實(shí)現(xiàn)示例詳解

    這篇文章主要為大家介紹了TensorFlow卷積神經(jīng)網(wǎng)絡(luò)AlexNet實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步
    2021-11-11
  • import?paddle報(bào)錯的成功解決方法

    import?paddle報(bào)錯的成功解決方法

    最近安裝paddle的時候遇到了些問題,這里給大家總結(jié)下,下面這篇文章主要給大家介紹了關(guān)于import?paddle報(bào)錯的成功解決方法,需要的朋友可以參考下
    2023-06-06
  • 簡單上手Python中裝飾器的使用

    簡單上手Python中裝飾器的使用

    這篇文章主要介紹了Python中裝飾器的使用,是Python進(jìn)階學(xué)習(xí)中的重要知識,需要的朋友可以參考下
    2015-07-07

最新評論