DataFrame的數據篩選

背景

        我需要從DataFrame數據結構中選取部分內容並重新組成一個DataFrame,例如:從一個班級成績總表中選出A類並重新組成一個列表。這麼簡單的功能我居然searching了一個多小時,網上垃圾資源太多了~~~最後還是自己總結出的經驗。(有更好的解決方法歡迎交流)

思路

        假設原有數據是table_raw, 創建一個空的dataframe(table_result), 然後遍歷整個table_raw,將符合需求的記錄添加到table_result中即可

涉及的知識點

  • DataFrame的創建
  • DataFrame元素提取
  • DataFrame與Series數據合併

示例代碼

import pandas as pd

# 原始輸入(示例)
name = ['張三','李四','王五','劉麻子']
age = [13,12,11,12]
score = [84,40,90,98]
df_raw = pd.DataFrame({'name':name,
                       'score':score,
                      'age':age})


df_result = pd.DataFrame(columns=df_raw.columns) # 創建空的表
for i in range(df_raw.shape[0]): #遍歷df_raw表
    score = int(df_raw.iloc[i]['score']) #獲取一條記錄中某個字段的值
    if score >= 90: #篩選邏輯
        df_result = df_result.append(df_raw.iloc[i], ignore_index = True)

print('raw:') 
print(df_raw)
print('result:')
print(df_result)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章