pandas 數(shù)據(jù)處理

  • 一. 刪除重復(fù)元素
  • 二. 映射
  • 三. 數(shù)據(jù)分析
  • 四. 異常值檢測(cè)和過(guò)濾
  • 五. 數(shù)據(jù)聚合

一. 刪除重復(fù)元素

  • duplicated(): 檢測(cè)數(shù)據(jù)重復(fù)行,返回series,若為不是第一次出現(xiàn)則為 True ,否則為 False
  • drop_duplicates() : 刪除重復(fù)行
    列名不能重復(fù),否則報(bào)錯(cuò);
df = pd.DataFrame(np.random.randint(0,2,size=(4,2)),
                   index=['張','李','王','張'],
                   columns=['js','python'])
print(df)
#    js  python
# 張   1       1
# 李   0       0
# 王   0       0
# 張   0       1

print(df.duplicated())
# 張    False
# 李    False
# 王     True
# 張    False
# dtype: bool

print(df.drop_duplicates())
#    js  python
# 張   1       1
# 李   0       0
# 張   0       1

print(df.drop_duplicates('js'))
#    js  python
# 張   1       1
# 李   0       0


二. 映射

1. replace():替換符合條件的值

參數(shù):

  • to_replace:{‘替換的原數(shù)據(jù)’:‘替換的目標(biāo)數(shù)據(jù)’}
  • value :替換的目標(biāo)數(shù)據(jù),多個(gè)數(shù)據(jù)替換為同一個(gè)時(shí)可采用
  • inplace
  • limit: 向前向后填充的最大限度
  • regex: 正則表達(dá)
  • method: ‘pad’, ‘ffill’, ‘bfill’, None 向前向后填充
df = pd.DataFrame(np.random.randint(0,2,size=(4,2)),
                   index=['張','李','王','張'],
                   columns=['js','python'])

print(df)
#    js  python
# 張   1       0
# 李   0       1
# 王   1       1
# 張   0       1

print(df.replace(to_replace=1,value=100))
#     js  python
# 張  100       0
# 李    0     100
# 王  100     100
# 張    0     100

print(df.replace({0:000,1:111}))
#     js  python
# 張  111       0
# 李    0     111
# 王  111     111
# 張    0     111
2. map():

map方法可以根據(jù)條件修改當(dāng)前列,還可以映射新一列數(shù)據(jù)
map可以使用方法和lambda表達(dá)式,不能使用sum之類(lèi)的函數(shù)
可以新建一列

df = pd.DataFrame(np.random.randint(0,2,size=(4,2)),
                   index=['張','李','王','張'],
                   columns=['js','python'])
print(df)
#    js  python
# 張   0       0
# 李   0       1
# 王   0       0
# 張   0       1

df['python'] = df['js'].map(lambda x:x+3)
print(df)
#    js  python
# 張   0       3
# 李   0       3
# 王   0       3
# 張   0       3

def judge(item):
    if(item>=1):
        return 'sucess'
    else: return 'fail'
df['python'] = df['js'].map(judge)
print(df)
#    js python
# 張   0   fail
# 李   0   fail
# 王   0   fail
# 張   0   fail

# 新增一列
df['c++'] = df['js'].map(lambda x:x+1)
print(df)
#    js python  c++
# 張   0   fail    1
# 李   0   fail    1
# 王   0   fail    1
# 張   0   fail    1
3. transform(): 與map類(lèi)似,根據(jù)某種規(guī)則算法,進(jìn)行批量修改
4. rename(): 替換索引
df = pd.DataFrame(np.random.randint(0,2,size=(4,2)),
                   index=['張','李','王','張'],
                   columns=['js','python'])
col = {'js':'c++'}
print(df.rename(columns=col))
#    c++  python
# 張    1       1
# 李    1       0
# 王    1       0
# 張    1       1

三. 數(shù)據(jù)分析

descibe() 函數(shù)

包含計(jì)數(shù),平均值,最大最小值,標(biāo)準(zhǔn)方差

df = pd.DataFrame(np.random.randint(0,100,size=(3,2)),
                   index=['張','李','王'],
                   columns=['js','python'])
print(df)
#    js  python
# 張  78       4
# 李  79      84
# 王  34      37
print(df.describe())
#               js     python
# count   3.000000   3.000000   ---計(jì)數(shù)
# mean   63.666667  41.666667   ---平均值
# std    25.696952  40.203648   ---標(biāo)準(zhǔn)方差
# min    34.000000   4.000000
# 25%    56.000000  20.500000
# 50%    78.000000  37.000000
# 75%    78.500000  60.500000
# max    79.000000  84.000000

print(df.max())
# js        34
# python    26
# dtype: int32

print(df.max().js)
# 34

四. 異常值檢測(cè)和過(guò)濾

df = pd.DataFrame(np.random.randint(0,100,size=(3,2)),
                 index=['張','李','王'],
                 columns=['js','python'])
print(df)
 js  python
# 張   9      26
# 李  39      39
# 王  92      66

print(df.std(axis=1))
# 張    12.020815
# 李     0.000000
# 王    18.384776
# dtype: float64

df1 = np.abs(df)>df.std()*3
df2 = df1.any(axis = 1)
print(df2)
# 張    False
# 李    False
# 王     True
# dtype: bool

print(df[df2])
#    js  python
# 王  92      66

df1 = np.abs(df)>df.std()*3 此句為本例異常檢測(cè)的標(biāo)準(zhǔn)(其值大于標(biāo)準(zhǔn)方差的3倍)
檢測(cè)結(jié)果:’王‘ 的成績(jī)異常


五. 數(shù)據(jù)聚合

DataFrame.groupby()
實(shí)例:
對(duì) item 列進(jìn)行分組,求取分組下各列的最大值

df = pd.DataFrame({'item':['apple','bananla','orange','apple','bananla'],
                   'price':[10,20,30,40,50],
                   'number':[30,20,10,5,0]})
print(df)
#       item  price  number
# 0    apple     10      30
# 1  bananla     20      20
# 2   orange     30      10
# 3    apple     40       5
# 4  bananla     50       0

g = df.groupby('item')
print(g.max())
#          price  number
# item
# apple       40      30
# bananla     50      20

獲取 item 分組下的 price 的平均值,返回為 series

print(g['price'].mean())
# item
# apple      25
# bananla    35
# orange     30
# Name: price, dtype: int64

將 price 的平均值 合并到原來(lái)的 dataframe中

price_mean = g['price'].mean()
price_mean = pd.DataFrame(price_mean)
price_mean.columns = ['price_mean']

print(pd.merge(df,price_mean,left_on='item',right_index=True))
#       item  price  number  price_mean
# 0    apple     10      30          25
# 3    apple     40       5          25
# 1  bananla     20      20          35
# 4  bananla     50       0          35
# 2   orange     30      10          30
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容