Pandas 用法匯編

50道練習(xí)帶你玩轉(zhuǎn)Pandas

王大毛

作者:王大毛,和鯨社區(qū)

出處:https://www.kesci.com/home/project/5ddc974ef41512002cec1dca

修改:黃海廣

Pandas 是基于 NumPy 的一種數(shù)據(jù)處理工具,該工具為了解決數(shù)據(jù)分析任務(wù)而創(chuàng)建。Pandas 納入了大量庫(kù)和一些標(biāo)準(zhǔn)的數(shù)據(jù)模型,提供了高效地操作大型數(shù)據(jù)集所需的函數(shù)和方法玫鸟。這些練習(xí)著重DataFrame和Series對(duì)象的基本操作,包括數(shù)據(jù)的索引、分組挺身、統(tǒng)計(jì)和清洗。

本文的代碼可以到github下載:https://github.com/fengdu78/Data-Science-Notes/tree/master/3.pandas/4.Pandas50

基本操作

1.導(dǎo)入 Pandas 庫(kù)并簡(jiǎn)寫為 pd锌仅,并輸出版本號(hào)

import pandas as pdpd.__version__
'0.22.0'

2. 從列表創(chuàng)建 Series

arr = [0, 1, 2, 3, 4]df = pd.Series(arr) # 如果不指定索引章钾,則默認(rèn)從 0 開(kāi)始df
0    01    12    23    34    4dtype: int64

3. 從字典創(chuàng)建 Series

d = {'a':1,'b':2,'c':3,'d':4,'e':5}df = pd.Series(d)df
a    1b    2c    3d    4e    5dtype: int64

4. 從 NumPy 數(shù)組創(chuàng)建 DataFrame

import numpy as npdates = pd.date_range('today', periods=6)  # 定義時(shí)間序列作為 indexnum_arr = np.random.randn(6, 4)  # 傳入 numpy 隨機(jī)數(shù)組columns = ['A', 'B', 'C', 'D']  # 將列表作為列名df = pd.DataFrame(num_arr, index=dates, columns=columns)df

|
| A | B | C | D |
| --- | --- | --- | --- | --- |
| 2020-01-10 22:46:01.642021 | 0.277099 | 0.665053 | 0.882637 | -0.598895 |
| 2020-01-11 22:46:01.642021 | 0.365233 | -2.529804 | -0.699849 | 0.159623 |
| 2020-01-12 22:46:01.642021 | -0.831850 | -2.099049 | -0.976407 | -0.342800 |
| 2020-01-13 22:46:01.642021 | 0.680800 | 1.682999 | 0.144469 | -2.503013 |
| 2020-01-14 22:46:01.642021 | -0.413880 | 0.876169 | -1.047877 | 0.996865 |
| 2020-01-15 22:46:01.642021 | 1.373956 | 0.029732 | -0.549268 | -0.287584 |

5. 從CSV中創(chuàng)建 DataFrame,分隔符為“热芹;”贱傀,編碼格式為gbk

df = pd.read_csv('test.csv', encoding='gbk', sep=';')
6\. 從字典對(duì)象創(chuàng)建DataFrame,并設(shè)置索引
import numpy as np
data = { 
'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'], 
'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],  
'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 
'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']
}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(data, index=labels)
df

|
| age | animal | priority | visits |
| --- | --- | --- | --- | --- |
| a | 2.5 | cat | yes | 1 |
| b | 3.0 | cat | yes | 3 |
| c | 0.5 | snake | no | 2 |
| d | NaN | dog | yes | 3 |
| e | 5.0 | dog | no | 2 |
| f | 2.0 | cat | no | 3 |
| g | 4.5 | snake | no | 1 |
| h | NaN | cat | yes | 1 |
| i | 7.0 | dog | no | 2 |
| j | 3.0 | dog | no | 1 |

7. 顯示df的基礎(chǔ)信息伊脓,包括行的數(shù)量耘沼;列名;每一列值的數(shù)量题涨、類型

df.info()
# 方法二
# df.describe()
<class 'pandas.core.frame.DataFrame'>
Index: 10 entries, a to j
Data columns (total 4 columns):
age  8 non-null float64
animal 10 non-null object
priority 10 non-null object 
visits  10 non-null int64  
dtypes: float64(1), int64(1), object(2)
memory usage: 400.0+ bytes

8. 展示df的前3行

df.iloc[:3]
# 方法二
#df.head(3)

|
| age | animal | priority | visits |
| --- | --- | --- | --- | --- |
| a | 2.5 | cat | yes | 1 |
| b | 3.0 | cat | yes | 3 |
| c | 0.5 | snake | no | 2 |

9. 取出df的animal和age列

df.loc[:, ['animal', 'age']]
# 方法二
# df[['animal', 'age']]

|
| animal | age |
| --- | --- | --- |
| a | cat | 2.5 |
| b | cat | 3.0 |
| c | snake | 0.5 |
| d | dog | NaN |
| e | dog | 5.0 |
| f | cat | 2.0 |
| g | snake | 4.5 |
| h | cat | NaN |
| i | dog | 7.0 |
| j | dog | 3.0 |

10. 取出索引為[3, 4, 8]行的animal和age列

df.loc[df.index[[3, 4, 8]], ['animal', 'age']]

|
| animal | age |
| --- | --- | --- |
| d | dog | NaN |
| e | dog | 5.0 |
| i | dog | 7.0 |

11. 取出age值大于3的行

df[df['age'] > 3]

|
| age | animal | priority | visits |
| --- | --- | --- | --- | --- |
| e | 5.0 | dog | no | 2 |
| g | 4.5 | snake | no | 1 |
| i | 7.0 | dog | no | 2 |

12. 取出age值缺失的行

df[df['age'].isnull()]

|
| age | animal | priority | visits |
| --- | --- | --- | --- | --- |
| d | NaN | dog | yes | 3 |
| h | NaN | cat | yes | 1 |

13.取出age在2,4間的行(不含)

df[(df['age']>2) & (df['age']>4)]# 方法二# df[df['age'].between(2, 4)]

|
| age | animal | priority | visits |
| --- | --- | --- | --- | --- |
| e | 5.0 | dog | no | 2 |
| g | 4.5 | snake | no | 1 |
| i | 7.0 | dog | no | 2 |

14. f 行的age改為1.5

df.loc['f', 'age'] = 1.5

15. 計(jì)算visits的總和

df['visits'].sum()
19

16. 計(jì)算每個(gè)不同種類animal的age的平均數(shù)

df.groupby('animal')['age'].mean()
animalcat      2.333333dog      5.000000snake    2.500000Name: age, dtype: float64

17. 在df中插入新行k认烁,然后刪除該行

#插入df.loc['k'] = [5.5, 'dog', 'no', 2]# 刪除df = df.drop('k')df

|
| age | animal | priority | visits |
| --- | --- | --- | --- | --- |
| a | 2.5 | cat | yes | 1 |
| b | 3.0 | cat | yes | 3 |
| c | 0.5 | snake | no | 2 |
| d | NaN | dog | yes | 3 |
| e | 5.0 | dog | no | 2 |
| f | 1.5 | cat | no | 3 |
| g | 4.5 | snake | no | 1 |
| h | NaN | cat | yes | 1 |
| i | 7.0 | dog | no | 2 |
| j | 3.0 | dog | no | 1 |

18. 計(jì)算df中每個(gè)種類animal的數(shù)量

df['animal'].value_counts()
dog      4cat      4snake    2Name: animal, dtype: int64

19. 先按age降序排列,后按visits升序排列

df.sort_values(by=['age', 'visits'], ascending=[False, True])

|
| age | animal | priority | visits |
| --- | --- | --- | --- | --- |
| i | 7.0 | dog | no | 2 |
| e | 5.0 | dog | no | 2 |
| g | 4.5 | snake | no | 1 |
| j | 3.0 | dog | no | 1 |
| b | 3.0 | cat | yes | 3 |
| a | 2.5 | cat | yes | 1 |
| f | 1.5 | cat | no | 3 |
| c | 0.5 | snake | no | 2 |
| h | NaN | cat | yes | 1 |
| d | NaN | dog | yes | 3 |

20. 將priority列中的yes, no替換為布爾值True, False

df['priority'] = df['priority'].map({'yes': True, 'no': False})df

|
| age | animal | priority | visits |
| --- | --- | --- | --- | --- |
| a | 2.5 | cat | True | 1 |
| b | 3.0 | cat | True | 3 |
| c | 0.5 | snake | False | 2 |
| d | NaN | dog | True | 3 |
| e | 5.0 | dog | False | 2 |
| f | 1.5 | cat | False | 3 |
| g | 4.5 | snake | False | 1 |
| h | NaN | cat | True | 1 |
| i | 7.0 | dog | False | 2 |
| j | 3.0 | dog | False | 1 |

21. 將animal列中的snake替換為python

df['animal'] = df['animal'].replace('snake', 'python')df

|
| age | animal | priority | visits |
| --- | --- | --- | --- | --- |
| a | 2.5 | cat | True | 1 |
| b | 3.0 | cat | True | 3 |
| c | 0.5 | python | False | 2 |
| d | NaN | dog | True | 3 |
| e | 5.0 | dog | False | 2 |
| f | 1.5 | cat | False | 3 |
| g | 4.5 | python | False | 1 |
| h | NaN | cat | True | 1 |
| i | 7.0 | dog | False | 2 |
| j | 3.0 | dog | False | 1 |

22. 對(duì)每種animal的每種不同數(shù)量visits纯蛾,計(jì)算平均age纤房,即,返回一個(gè)表格翻诉,行是aniaml種類炮姨,列是visits數(shù)量,表格值是行動(dòng)物種類列訪客數(shù)量的平均年齡

df.pivot_table(index='animal', columns='visits', values='age', aggfunc='mean')
visits 1 2 3
animal
--- --- --- ---
cat 2.5 NaN 2.25
dog 3.0 6.0 NaN
python 4.5 0.5 NaN

進(jìn)階操作

23. 有一列整數(shù)列A的DatraFrame碰煌,刪除數(shù)值重復(fù)的行

df = pd.DataFrame({'A': [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7]})print(df)df1 = df.loc[df['A'].shift() != df['A']]# 方法二# df1 = df.drop_duplicates(subset='A')print(df1)
    A0   11   22   23   34   45   56   57   58   69   710  7   A0  11  23  34  45  58  69  7

24. 一個(gè)全數(shù)值DatraFrame舒岸,每個(gè)數(shù)字減去該行的平均數(shù)

df = pd.DataFrame(np.random.random(size=(5, 3)))print(df)df1 = df.sub(df.mean(axis=1), axis=0)print(df1)
          0         1         20  0.465407  0.152497  0.8611741  0.623682  0.627339  0.4956522  0.835176  0.862376  0.6930473  0.319698  0.306709  0.6540634  0.234855  0.194232  0.438597          0         1         20 -0.027619 -0.340529  0.3681481  0.041457  0.045115 -0.0865722  0.038310  0.065509 -0.1038193 -0.107125 -0.120114  0.2272394 -0.054373 -0.094996  0.149368

25. 一個(gè)有5列的DataFrame,求哪一列的和最小

df = pd.DataFrame(np.random.random(size=(5, 5)), columns=list('abcde'))print(df)df.sum().idxmin()
          a         b         c         d         e0  0.653658  0.730994  0.223025  0.456730  0.2882831  0.937546  0.640995  0.197359  0.671524  0.0060352  0.392762  0.174955  0.053928  0.318634  0.4645343  0.741499  0.197861  0.988105  0.633780  0.9142504  0.469285  0.309043  0.162127  0.032480  0.863017'c'

26. 給定DataFrame芦圾,求A列每個(gè)值的前3大的B的值的和

df = pd.DataFrame({'A': list('aaabbcaabcccbbc'),                   'B': [12,345,3,1,45,14,4,52,54,23,235,21,57,3,87]})print(df)df1 = df.groupby('A')['B'].nlargest(3).sum(level=0)print(df1)
    A    B0   a   121   a  3452   a    33   b    14   b   455   c   146   a    47   a   528   b   549   c   2310  c  23511  c   2112  b   5713  b    314  c   87Aa    409b    156c    345Name: B, dtype: int64

27. 給定DataFrame吁津,有列A, B,A的值在1-100(含),對(duì)A列每10步長(zhǎng)碍脏,求對(duì)應(yīng)的B的和

df = pd.DataFrame({    'A': [1, 2, 11, 11, 33, 34, 35, 40, 79, 99],    'B': [1, 2, 11, 11, 33, 34, 35, 40, 79, 99]})print(df)df1 = df.groupby(pd.cut(df['A'], np.arange(0, 101, 10)))['B'].sum()print(df1)
    A   B0   1   11   2   22  11  113  11  114  33  335  34  346  35  357  40  408  79  799  99  99A(0, 10]        3(10, 20]      22(20, 30]       0(30, 40]     142(40, 50]       0(50, 60]       0(60, 70]       0(70, 80]      79(80, 90]       0(90, 100]     99Name: B, dtype: int64

28. 給定DataFrame梭依,計(jì)算每個(gè)元素至左邊最近的0(或者至開(kāi)頭)的距離,生成新列y

df = pd.DataFrame({'X': [7, 2, 0, 3, 4, 2, 5, 0, 3, 4]})# 方法一x = (df['X'] != 0).cumsum()y = x != x.shift()df['Y'] = y.groupby((y != y.shift()).cumsum()).cumsum()print(df)
   X    Y0  7  1.01  2  2.02  0  0.03  3  1.04  4  2.05  2  3.06  5  4.07  0  0.08  3  1.09  4  2.0
# 方法二df['Y'] = df.groupby((df['X'] == 0).cumsum()).cumcount()first_zero_idx = (df['X'] == 0).idxmax()df['Y'].iloc[0:first_zero_idx] += 1print(df)
   X  Y0  7  11  2  22  0  03  3  14  4  25  2  36  5  47  0  08  3  19  4  2

29. 一個(gè)全數(shù)值的DataFrame典尾,返回最大3個(gè)值的坐標(biāo)

df = pd.DataFrame(np.random.random(size=(5, 3)))print(df)df.unstack().sort_values()[-3:].index.tolist()
          0         1         20  0.974321  0.454025  0.0188151  0.323491  0.468609  0.8344242  0.340960  0.826835  0.5032523  0.812414  0.202745  0.9651684  0.633172  0.270281  0.915212[(2, 4), (2, 3), (0, 0)]

30. 給定DataFrame役拴,將負(fù)值代替為同組的平均值

df = pd.DataFrame({    'grps':    list('aaabbcaabcccbbc'),    'vals': [-12, 345, 3, 1, 45, 14, 4, -52, 54, 23, -235, 21, 57, 3, 87]})print(df)def replace(group):    mask = group < 0    group[mask] = group[~mask].mean()    return groupdf['vals'] = df.groupby(['grps'])['vals'].transform(replace)print(df)
   grps  vals0     a   -121     a   3452     a     33     b     14     b    455     c    146     a     47     a   -528     b    549     c    2310    c  -23511    c    2112    b    5713    b     314    c    87   grps        vals0     a  117.3333331     a  345.0000002     a    3.0000003     b    1.0000004     b   45.0000005     c   14.0000006     a    4.0000007     a  117.3333338     b   54.0000009     c   23.00000010    c   36.25000011    c   21.00000012    b   57.00000013    b    3.00000014    c   87.000000

31. 計(jì)算3位滑動(dòng)窗口的平均值,忽略NAN

df = pd.DataFrame({    'group': list('aabbabbbabab'),    'value': [1, 2, 3, np.nan, 2, 3, np.nan, 1, 7, 3, np.nan, 8]})print(df)g1 = df.groupby(['group'])['value']g2 = df.fillna(0).groupby(['group'])['value']s = g2.rolling(3, min_periods=1).sum() / g1.rolling(3, min_periods=1).count()s.reset_index(level=0, drop=True).sort_index()
   group  value0      a    1.01      a    2.02      b    3.03      b    NaN4      a    2.05      b    3.06      b    NaN7      b    1.08      a    7.09      b    3.010     a    NaN11     b    8.00     1.0000001     1.5000002     3.0000003     3.0000004     1.6666675     3.0000006     3.0000007     2.0000008     3.6666679     2.00000010    4.50000011    4.000000Name: value, dtype: float64

Series 和 Datetime索引

32. 創(chuàng)建Series s钾埂,將2015所有工作日作為隨機(jī)值的索引

dti = pd.date_range(start='2015-01-01', end='2015-12-31', freq='B')s = pd.Series(np.random.rand(len(dti)), index=dti)s.head(10)
2015-01-01    0.5034582015-01-02    0.1941852015-01-05    0.5509302015-01-06    0.1743092015-01-07    0.3169112015-01-08    0.2883852015-01-09    0.2932852015-01-12    0.3404362015-01-13    0.6300092015-01-14    0.076130Freq: B, dtype: float64

33. 所有禮拜三的值求和

s[s.index.weekday == 2].sum()
27.272318047689705

34. 求每個(gè)自然月的平均數(shù)

s.resample('M').mean()
2015-01-31    0.3754172015-02-28    0.5515602015-03-31    0.5407722015-04-30    0.4509572015-05-31    0.3691192015-06-30    0.5886252015-07-31    0.5843582015-08-31    0.6097512015-09-30    0.5112852015-10-31    0.5555462015-11-30    0.5287772015-12-31    0.574317Freq: M, dtype: float64

35. 每連續(xù)4個(gè)月為一組河闰,求最大值所在的日期

s.groupby(pd.Grouper(freq='4M')).idxmax()
2015-01-31   2015-01-152015-05-31   2015-02-042015-09-30   2015-06-022016-01-31   2015-12-08dtype: datetime64[ns]

36. 創(chuàng)建2015-2016每月第三個(gè)星期四的序列

pd.date_range('2015-01-01', '2016-12-31', freq='WOM-3THU')#數(shù)據(jù)清洗df = pd.DataFrame({'From_To': ['LoNDon_paris', 'MAdrid_miLAN', 'londON_StockhOlm',                               'Budapest_PaRis', 'Brussels_londOn'],              'FlightNumber': [10045, np.nan, 10065, np.nan, 10085],              'RecentDelays': [[23, 47], [], [24, 43, 87], [13], [67, 32]],                   'Airline': ['KLM(!)', '<Air France> (12)', '(British Airways. )',                               '12\. Air France', '"Swiss Air"']})df

|
| Airline | FlightNumber | From_To | RecentDelays |
| --- | --- | --- | --- | --- |
| 0 | KLM(!) | 10045.0 | LoNDon_paris | [23, 47] |
| 1 | <Air France> (12) | NaN | MAdrid_miLAN | [] |
| 2 | (British Airways. ) | 10065.0 | londON_StockhOlm | [24, 43, 87] |
| 3 | 12. Air France | NaN | Budapest_PaRis | [13] |
| 4 | "Swiss Air" | 10085.0 | Brussels_londOn | [67, 32] |

37. FlightNumber列中有些值缺失了,他們本來(lái)應(yīng)該是每一行增加10褥紫,填充缺失的數(shù)值姜性,并且令數(shù)據(jù)類型為整數(shù)

df['FlightNumber'] = df['FlightNumber'].interpolate().astype(int)df

|
| Airline | FlightNumber | From_To | RecentDelays |
| --- | --- | --- | --- | --- |
| 0 | KLM(!) | 10045 | LoNDon_paris | [23, 47] |
| 1 | <Air France> (12) | 10055 | MAdrid_miLAN | [] |
| 2 | (British Airways. ) | 10065 | londON_StockhOlm | [24, 43, 87] |
| 3 | 12. Air France | 10075 | Budapest_PaRis | [13] |
| 4 | "Swiss Air" | 10085 | Brussels_londOn | [67, 32] |

38. 將From_To列從_分開(kāi),分成From, To兩列髓考,并刪除原始列

temp = df.From_To.str.split('_', expand=True)temp.columns = ['From', 'To']df = df.join(temp)df = df.drop('From_To', axis=1)df

|
| Airline | FlightNumber | RecentDelays | From | To |
| --- | --- | --- | --- | --- | --- |
| 0 | KLM(!) | 10045 | [23, 47] | LoNDon | paris |
| 1 | <Air France> (12) | 10055 | [] | MAdrid | miLAN |
| 2 | (British Airways. ) | 10065 | [24, 43, 87] | londON | StockhOlm |
| 3 | 12. Air France | 10075 | [13] | Budapest | PaRis |
| 4 | "Swiss Air" | 10085 | [67, 32] | Brussels | londOn |

39. 將From, To大小寫統(tǒng)一首字母大寫其余小寫

df['From'] = df['From'].str.capitalize()df['To'] = df['To'].str.capitalize()df

|
| Airline | FlightNumber | RecentDelays | From | To |
| --- | --- | --- | --- | --- | --- |
| 0 | KLM(!) | 10045 | [23, 47] | London | Paris |
| 1 | <Air France> (12) | 10055 | [] | Madrid | Milan |
| 2 | (British Airways. ) | 10065 | [24, 43, 87] | London | Stockholm |
| 3 | 12. Air France | 10075 | [13] | Budapest | Paris |
| 4 | "Swiss Air" | 10085 | [67, 32] | Brussels | London |

40. Airline列部念,有一些多余的標(biāo)點(diǎn)符號(hào),需要提取出正確的航司名稱氨菇。舉例:'(British Airways. )' 應(yīng)該改為 'British Airways'.

df['Airline'] = df['Airline'].str.extract(    '([a-zA-Z\s]+)', expand=False).str.strip()df

|
| Airline | FlightNumber | RecentDelays | From | To |
| --- | --- | --- | --- | --- | --- |
| 0 | KLM | 10045 | [23, 47] | London | Paris |
| 1 | Air France | 10055 | [] | Madrid | Milan |
| 2 | British Airways | 10065 | [24, 43, 87] | London | Stockholm |
| 3 | Air France | 10075 | [13] | Budapest | Paris |
| 4 | Swiss Air | 10085 | [67, 32] | Brussels | London |

41. Airline列儡炼,數(shù)據(jù)被以列表的形式錄入,但是我們希望每個(gè)數(shù)字被錄入成單獨(dú)一列查蓉,delay_1, delay_2, ...沒(méi)有的用NAN替代乌询。

delays = df['RecentDelays'].apply(pd.Series)delays.columns = ['delay_{}'.format(n) for n in range(1, len(delays.columns)+1)]df = df.drop('RecentDelays', axis=1).join(delays)df

|
| Airline | FlightNumber | From | To | delay_1 | delay_2 | delay_3 |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | KLM | 10045 | London | Paris | 23.0 | 47.0 | NaN |
| 1 | Air France | 10055 | Madrid | Milan | NaN | NaN | NaN |
| 2 | British Airways | 10065 | London | Stockholm | 24.0 | 43.0 | 87.0 |
| 3 | Air France | 10075 | Budapest | Paris | 13.0 | NaN | NaN |
| 4 | Swiss Air | 10085 | Brussels | London | 67.0 | 32.0 | NaN |

層次化索引

42. 用 letters = ['A', 'B', 'C']和 numbers = list(range(10))的組合作為系列隨機(jī)值的層次化索引

letters = ['A', 'B', 'C']numbers = list(range(4))mi = pd.MultiIndex.from_product([letters, numbers])s = pd.Series(np.random.rand(12), index=mi)s
A  0    0.250785   1    0.146978   2    0.596062   3    0.064608B  0    0.709660   1    0.515778   2    0.483163   3    0.524490C  0    0.360434   1    0.987620   2    0.527151   3    0.636960dtype: float64

43. 檢查s是否是字典順序排序的

s.index.is_lexsorted()# 方法二# s.index.lexsort_depth == s.index.nlevels
True

44. 選擇二級(jí)索引為1, 3的行

s.loc[:, [1, 3]]
A  1    0.146978   3    0.064608B  1    0.515778   3    0.524490C  1    0.987620   3    0.636960dtype: float64

45. 對(duì)s進(jìn)行切片操作,取一級(jí)索引至B豌研,二級(jí)索引從2開(kāi)始到最后

s.loc[pd.IndexSlice[:'B', 2:]]# 方法二# s.loc[slice(None, 'B'), slice(2, None)]
A  2    0.596062   3    0.064608B  2    0.483163   3    0.524490dtype: float64

46. 計(jì)算每個(gè)一級(jí)索引的和(A, B, C每一個(gè)的和)

s.sum(level=0)#方法二#s.unstack().sum(axis=0)
A    1.058433B    2.233091C    2.512164dtype: float64

47. 交換索引等級(jí)妹田,新的Series是字典順序嗎?不是的話請(qǐng)排序

new_s = s.swaplevel(0, 1)print(new_s)print(new_s.index.is_lexsorted())new_s = new_s.sort_index()print(new_s)
0  A    0.2507851  A    0.1469782  A    0.5960623  A    0.0646080  B    0.7096601  B    0.5157782  B    0.4831633  B    0.5244900  C    0.3604341  C    0.9876202  C    0.5271513  C    0.636960dtype: float64False0  A    0.250785   B    0.709660   C    0.3604341  A    0.146978   B    0.515778   C    0.9876202  A    0.596062   B    0.483163   C    0.5271513  A    0.064608   B    0.524490   C    0.636960dtype: float64
## 可視化import matplotlib.pyplot as pltdf = pd.DataFrame({"xs": [1, 5, 2, 8, 1], "ys": [4, 2, 1, 9, 6]})plt.style.use('ggplot')

48. 畫出df的散點(diǎn)圖

df.plot.scatter("xs", "ys", color = "black", marker = "x")
<matplotlib.axes._subplots.AxesSubplot at 0x1f188ddacc0>
image.gif

49. 可視化指定4維DataFrame

df = pd.DataFrame({    "productivity": [5, 2, 3, 1, 4, 5, 6, 7, 8, 3, 4, 8, 9],    "hours_in": [1, 9, 6, 5, 3, 9, 2, 9, 1, 7, 4, 2, 2],    "happiness": [2, 1, 3, 2, 3, 1, 2, 3, 1, 2, 2, 1, 3],    "caffienated": [0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0]})df.plot.scatter(    "hours_in", "productivity", s=df.happiness * 100, c=df.caffienated)
<matplotlib.axes._subplots.AxesSubplot at 0x1f18aea4c18>
image.gif

50. 在同一個(gè)圖中可視化2組數(shù)據(jù)鹃共,共用X軸秆麸,但y軸不同

df = pd.DataFrame({    "revenue": [57, 68, 63, 71, 72, 90, 80, 62, 59, 51, 47, 52],    "advertising":    [2.1, 1.9, 2.7, 3.0, 3.6, 3.2, 2.7, 2.4, 1.8, 1.6, 1.3, 1.9],    "month":    range(12)})ax = df.plot.bar("month", "revenue", color="green")df.plot.line("month", "advertising", secondary_y=True, ax=ax)ax.set_xlim((-1, 12))
(-1, 12)
image.gif

本文的代碼可以到github下載:https://github.com/fengdu78/Data-Science-Notes/tree/master/3.pandas/4.Pandas50

image.gif

備注:公眾號(hào)菜單包含了整理了一本****AI小抄非常適合在通勤路上用學(xué)習(xí)及汉。

image.gif

<pre style="margin: 10px 0px; padding: 0px; max-width: 100%; box-sizing: border-box !important; word-wrap: break-word !important;">

往期精彩回顧

備注:加入本站微信群或者qq群,請(qǐng)回復(fù)“加群

加入知識(shí)星球(4500+用戶屯烦,ID:92416895)坷随,請(qǐng)回復(fù)“知識(shí)星球

</pre>

喜歡文章,點(diǎn)個(gè)****在看

image.gif

閱讀 143

在看

image

寫下你的留言

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末驻龟,一起剝皮案震驚了整個(gè)濱河市温眉,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌翁狐,老刑警劉巖类溢,帶你破解...
    沈念sama閱讀 221,695評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡闯冷,警方通過(guò)查閱死者的電腦和手機(jī)砂心,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)蛇耀,“玉大人辩诞,你說(shuō)我怎么就攤上這事》牡樱” “怎么了译暂?”我有些...
    開(kāi)封第一講書人閱讀 168,130評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)撩炊。 經(jīng)常有香客問(wèn)我外永,道長(zhǎng),這世上最難降的妖魔是什么拧咳? 我笑而不...
    開(kāi)封第一講書人閱讀 59,648評(píng)論 1 297
  • 正文 為了忘掉前任伯顶,我火速辦了婚禮,結(jié)果婚禮上呛踊,老公的妹妹穿的比我還像新娘砾淌。我一直安慰自己,他們只是感情好谭网,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,655評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布汪厨。 她就那樣靜靜地躺著,像睡著了一般愉择。 火紅的嫁衣襯著肌膚如雪劫乱。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 52,268評(píng)論 1 309
  • 那天锥涕,我揣著相機(jī)與錄音衷戈,去河邊找鬼。 笑死层坠,一個(gè)胖子當(dāng)著我的面吹牛殖妇,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播破花,決...
    沈念sama閱讀 40,835評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼谦趣,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了座每?” 一聲冷哼從身側(cè)響起前鹅,我...
    開(kāi)封第一講書人閱讀 39,740評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎峭梳,沒(méi)想到半個(gè)月后舰绘,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,286評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,375評(píng)論 3 340
  • 正文 我和宋清朗相戀三年捂寿,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了口四。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,505評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡者蠕,死狀恐怖窃祝,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情踱侣,我是刑警寧澤粪小,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站抡句,受9級(jí)特大地震影響探膊,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜待榔,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,873評(píng)論 3 333
  • 文/蒙蒙 一逞壁、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧锐锣,春花似錦腌闯、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 32,357評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至斤彼,卻和暖如春分瘦,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背琉苇。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,466評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工嘲玫, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人并扇。 一個(gè)月前我還...
    沈念sama閱讀 48,921評(píng)論 3 376
  • 正文 我出身青樓去团,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親穷蛹。 傳聞我的和親對(duì)象是個(gè)殘疾皇子土陪,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,515評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容