python數據科學(八):pandas基礎—— 丟棄、apply applymap、唯一性

丟棄

  • 丟棄行 axis=0
  • 丟棄列 axis=1
import pandas as pd
import numpy as np

## 丟棄部分數據
df = pd.DataFrame(np.random.randn(4, 6), index=list('ABCD'), columns=['one', 'two', 'three', 'four', 'five', 'six'])
print('丟棄')
print(df)
print(df.drop('A'))
df2 = df.drop(['two', 'four'], axis=1)
print(df2)

在這裏插入圖片描述

apply&appymap函數

  • apply: 將數據按行或列進行計算,可標量可序列
    默認按列操作 axis=0
    按行操作 axis=1
  • applymap: 將數據按元素爲進行計算
import pandas as pd
import numpy as np

### 函數應用
df = pd.DataFrame(np.arange(12).reshape(4, 3), index=['one', 'two', 'three', 'four'], columns=list('ABC'))
print('函數應用')


# apply
##標量
# 每一列作爲一個 Series 作爲參數傳遞給 lambda 函數
df.apply(lambda x: x.max() - x.min())
print(df)
# 每一行作爲一個 Series 作爲參數傳遞給 lambda 函數
df.apply(lambda x: x.max() - x.min(), axis=1)
print(df)

##序列
def min_max(x):
    return pd.Series([x.min(), x.max()], index=['min', 'max'])
df.apply(min_max, axis=1)



# applymap: 逐元素運算
df = pd.DataFrame(np.random.randn(4, 3), index=['one', 'two', 'three', 'four'], columns=list('ABC'))
print('applymap函數')
##只顯示小數點前兩位
formater = '{0:.02f}'.format
print(df.applymap(formater))

在這裏插入圖片描述

數據唯一性及成員資格

適用於 Series

### 數據唯一性及成員資格
s = pd.Series(list('abbcdabacad'))
print('數據唯一性及成員資格')
print(s.unique())
print(s.value_counts())
inin=s.isin(['a', 'b', 'c'])
print(inin)

在這裏插入圖片描述

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