master
/ 练习题-Pandas.ipynb

练习题-Pandas.ipynb @96fc089view markup · raw · history · blame

Notebook

Pandas 是基于 NumPy 的一种数据处理工具,该工具为了解决数据分析任务而创建。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的函数和方法。 这些练习着重DataFrame和Series对象的基本操作,包括数据的索引、分组、统计和清洗。

基本操作

  1. 导入 Pandas 库并简写为 pd,并输出版本号
In [1]:
import pandas as pd
import numpy as np
pd.__version__
Out[1]:
'0.24.2'

2.从列表创建 Series

In [2]:
arr = [0, 1, 2, 3, 4]
df = pd.Series(arr) # 如果不指定索引,则默认从 0 开始
df
Out[2]:
0    0
1    1
2    2
3    3
4    4
dtype: int64

3.从字典创建 Series

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

4.从 NumPy 数组创建 DataFrame

In [4]:
dates = pd.date_range('today',periods=6) # 定义时间序列作为 index
num_arr = np.random.randn(6,4) # 传入 numpy 随机数组
columns = ['A','B','C','D'] # 将列表作为列名
df1 = pd.DataFrame(num_arr, index = dates, columns = columns)
df1
Out[4]:
A B C D
2020-11-25 19:52:19.649803 -2.030876 -1.268538 -0.558541 -0.900418
2020-11-26 19:52:19.649803 -1.527629 -0.703445 0.101752 0.847650
2020-11-27 19:52:19.649803 1.778669 -0.726840 0.179889 0.900710
2020-11-28 19:52:19.649803 0.632184 0.156482 0.865383 -1.155356
2020-11-29 19:52:19.649803 0.092894 0.157272 -1.733493 -1.259203
2020-11-30 19:52:19.649803 -1.937439 0.120771 -1.964980 -1.700180

5.从CSV中创建 DataFrame,分隔符为;,编码格式为gbk

In [5]:
# df = pd.read_csv('test.csv', encoding='gbk, sep=';')

6.从字典对象data创建DataFrame,设置索引为labels

In [6]:
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']
In [7]:
df = pd.DataFrame(data, index=labels)
df
Out[7]:
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.显示DataFrame的基础信息,包括行的数量;列名;每一列值的数量、类型

In [8]:
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行

In [9]:
df.iloc[:3]
# 方法二
#df.head(3)
Out[9]:
age animal priority visits
a 2.5 cat yes 1
b 3.0 cat yes 3
c 0.5 snake no 2

9.取出dfanimalage

In [10]:
df.loc[:, ['animal', 'age']]
# 方法二
# df[['animal', 'age']]
Out[10]:
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]行的animalage

In [11]:
df.loc[df.index[[3, 4, 8]], ['animal', 'age']]
Out[11]:
animal age
d dog NaN
e dog 5.0
i dog 7.0

11.取出age值大于3的行

In [12]:
df[df['age'] > 3]
Out[12]:
age animal priority visits
e 5.0 dog no 2
g 4.5 snake no 1
i 7.0 dog no 2

12.取出age值缺失的行

In [13]:
df[df['age'].isnull()]
Out[13]:
age animal priority visits
d NaN dog yes 3
h NaN cat yes 1

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

In [14]:
df[(df['age']>2) & (df['age']<4)]
# 方法二
#df[df['age'].between(2, 4)]
Out[14]:
age animal priority visits
a 2.5 cat yes 1
b 3.0 cat yes 3
j 3.0 dog no 1

14.f行的age改为1.5

In [15]:
df.loc['f', 'age'] = 1.5

15.计算visits的总和

In [16]:
df['visits'].sum()
Out[16]:
19

16.计算每个不同种类animalage的平均数

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

17.计算df中每个种类animal的数量

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

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

In [19]:
df.sort_values(by=['age', 'visits'], ascending=[False, True])
Out[19]:
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

19.将priority列中的yes, no替换为布尔值True, False

In [20]:
df['priority'] = df['priority'].map({'yes': True, 'no': False})
df
Out[20]:
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

20.将animal列中的snake替换为python

In [21]:
df['animal'] = df['animal'].replace('snake', 'python')
df
Out[21]:
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

21.对每种animal的每种不同数量visits,计算平均age,即,返回一个表格,行是aniaml种类,列是visits数量,表格值是行动物种类列访客数量的平均年龄

In [22]:
df.dtypes
Out[22]:
age         float64
animal       object
priority       bool
visits        int64
dtype: object
In [23]:
df.age=df.age.astype(float)
In [24]:
df.pivot_table(index='animal', columns='visits', values='age', aggfunc='mean')
Out[24]:
visits 1 2 3
animal
cat 2.5 NaN 2.25
dog 3.0 6.0 NaN
python 4.5 0.5 NaN

22.在df中插入新行k,然后删除该行

In [25]:
#插入
df.loc['k'] = [5.5, 'dog', 'no', 2]
# 删除
df = df.drop('k')
df
Out[25]:
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

进阶操作

23.有一列整数列A的DatraFrame,删除数值重复的行

In [26]:
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)
    A
0   1
1   2
2   2
3   3
4   4
5   5
6   5
7   5
8   6
9   7
10  7
   A
0  1
1  2
3  3
4  4
5  5
8  6
9  7

24.一个全数值DatraFrame,每个数字减去该行的平均数

In [27]:
df = pd.DataFrame(np.random.random(size=(5, 3)))
print(df)
df1 = df.sub(df.mean(axis=1), axis=0)
print(df1)
          0         1         2
0  0.414453  0.332157  0.856186
1  0.163896  0.089443  0.593890
2  0.526212  0.781033  0.299327
3  0.405021  0.890150  0.575210
4  0.516062  0.485737  0.584763
          0         1         2
0 -0.119812 -0.202108  0.321921
1 -0.118514 -0.192967  0.311480
2 -0.009312  0.245509 -0.236198
3 -0.218440  0.266689 -0.048250
4 -0.012792 -0.043117  0.055909

25.一个有5列的DataFrame,求哪一列的和最小

In [28]:
df = pd.DataFrame(np.random.random(size=(5, 5)), columns=list('abcde'))
print(df)
df.sum().idxmin()
          a         b         c         d         e
0  0.497311  0.702727  0.317818  0.246678  0.761391
1  0.757598  0.135243  0.023186  0.181558  0.360602
2  0.002264  0.116232  0.221348  0.717638  0.289913
3  0.048115  0.909258  0.013615  0.080099  0.722705
4  0.138972  0.687775  0.540898  0.306161  0.444953
Out[28]:
'c'

26.给定DataFrame,求A列每个值的前3大的B的和

In [29]:
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    B
0   a   12
1   a  345
2   a    3
3   b    1
4   b   45
5   c   14
6   a    4
7   a   52
8   b   54
9   c   23
10  c  235
11  c   21
12  b   57
13  b    3
14  c   87
A
a    409
b    156
c    345
Name: B, dtype: int64

27.给定DataFrame,有列A, BA的值在1-100(含),对A列每10步长,求对应的B的和

In [30]:
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   B
0   1   1
1   2   2
2  11  11
3  11  11
4  33  33
5  34  34
6  35  35
7  40  40
8  79  79
9  99  99
A
(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]     99
Name: B, dtype: int64

28.给定DataFrame,计算每个元素至左边最近的0(或者至开头)的距离,生成新列y

In [31]:
df = pd.DataFrame({'X': [7, 2, 0, 3, 4, 2, 5, 0, 3, 4]})

izero = np.r_[-1, (df['X'] == 0).to_numpy().nonzero()[0]] # 标记0的位置
idx = np.arange(len(df))
df['Y'] = idx - izero[np.searchsorted(izero - 1, idx) - 1]
print(df)

# 方法二
# x = (df['X'] != 0).cumsum()
# y = x != x.shift()
# df['Y'] = y.groupby((y != y.shift()).cumsum()).cumsum()

# 方法三
# df['Y'] = df.groupby((df['X'] == 0).cumsum()).cumcount()
#first_zero_idx = (df['X'] == 0).idxmax()
# df['Y'].iloc[0:first_zero_idx] += 1
   X  Y
0  7  1
1  2  2
2  0  0
3  3  1
4  4  2
5  2  3
6  5  4
7  0  0
8  3  1
9  4  2

29.一个全数值的DataFrame,返回最大3值的坐标

In [32]:
df = pd.DataFrame(np.random.random(size=(5, 3)))
print(df)
df.unstack().sort_values()[-3:].index.tolist()
          0         1         2
0  0.357183  0.569268  0.115802
1  0.605917  0.881550  0.593334
2  0.830468  0.072343  0.661204
3  0.811008  0.985117  0.550789
4  0.091020  0.296938  0.421596
Out[32]:
[(0, 2), (1, 1), (1, 3)]

30.给定DataFrame,将负值代替为同组的平均值

In [33]:
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 group

df['vals'] = df.groupby(['grps'])['vals'].transform(replace)
print(df)
   grps  vals
0     a   -12
1     a   345
2     a     3
3     b     1
4     b    45
5     c    14
6     a     4
7     a   -52
8     b    54
9     c    23
10    c  -235
11    c    21
12    b    57
13    b     3
14    c    87
   grps        vals
0     a  117.333333
1     a  345.000000
2     a    3.000000
3     b    1.000000
4     b   45.000000
5     c   14.000000
6     a    4.000000
7     a  117.333333
8     b   54.000000
9     c   23.000000
10    c   36.250000
11    c   21.000000
12    b   57.000000
13    b    3.000000
14    c   87.000000

31.计算3位滑动窗口的平均值,忽略NAN

In [34]:
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  value
0      a    1.0
1      a    2.0
2      b    3.0
3      b    NaN
4      a    2.0
5      b    3.0
6      b    NaN
7      b    1.0
8      a    7.0
9      b    3.0
10     a    NaN
11     b    8.0
Out[34]:
0     1.000000
1     1.500000
2     3.000000
3     3.000000
4     1.666667
5     3.000000
6     3.000000
7     2.000000
8     3.666667
9     2.000000
10    4.500000
11    4.000000
Name: value, dtype: float64

Series 和 Datetime索引

32.创建Series s,将2015所有工作日作为随机值的索引

In [35]:
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)
Out[35]:
2015-01-01    0.896401
2015-01-02    0.789480
2015-01-05    0.271381
2015-01-06    0.740503
2015-01-07    0.241424
2015-01-08    0.644122
2015-01-09    0.599708
2015-01-12    0.714903
2015-01-13    0.285152
2015-01-14    0.574001
Freq: B, dtype: float64

33.所有礼拜三的值求和

In [36]:
s[s.index.weekday == 2].sum() 
Out[36]:
27.08213095254659

34.求每个自然月的平均数

In [37]:
s.resample('M').mean()
Out[37]:
2015-01-31    0.474092
2015-02-28    0.421380
2015-03-31    0.676973
2015-04-30    0.427968
2015-05-31    0.638426
2015-06-30    0.561239
2015-07-31    0.536794
2015-08-31    0.500563
2015-09-30    0.548050
2015-10-31    0.592157
2015-11-30    0.467826
2015-12-31    0.548842
Freq: M, dtype: float64

35.每连续4个月为一组,求最大值所在的日期

In [38]:
s.groupby(pd.Grouper(freq='4M')).idxmax()
Out[38]:
2015-01-31   2015-01-01
2015-05-31   2015-03-11
2015-09-30   2015-07-03
2016-01-31   2015-11-23
Freq: 4M, dtype: datetime64[ns]

36.创建2015-2016每月第三个星期四的序列

In [39]:
pd.date_range('2015-01-01', '2016-12-31', freq='WOM-3THU')
Out[39]:
DatetimeIndex(['2015-01-15', '2015-02-19', '2015-03-19', '2015-04-16',
               '2015-05-21', '2015-06-18', '2015-07-16', '2015-08-20',
               '2015-09-17', '2015-10-15', '2015-11-19', '2015-12-17',
               '2016-01-21', '2016-02-18', '2016-03-17', '2016-04-21',
               '2016-05-19', '2016-06-16', '2016-07-21', '2016-08-18',
               '2016-09-15', '2016-10-20', '2016-11-17', '2016-12-15'],
              dtype='datetime64[ns]', freq='WOM-3THU')

数据清洗

In [40]:
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
Out[40]:
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列中有些值缺失了,他们本来应该是每一行增加10,填充缺失的数值,并且令数据类型为整数

In [41]:
df['FlightNumber'] = df['FlightNumber'].interpolate().astype(int)
df
Out[41]:
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列从_分开,分成From, To两列,并删除原始列

In [42]:
temp = df.From_To.str.split('_', expand=True)
temp.columns = ['From', 'To']
df = df.join(temp)
df = df.drop('From_To', axis=1)
df
Out[42]:
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大小写统一

In [43]:
df['From'] = df['From'].str.capitalize()
df['To'] = df['To'].str.capitalize()
df
Out[43]:
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列,有一些多余的标点符号,需要提取出正确的航司名称。举例:'(British Airways. )' 应该改为 'British Airways'.

In [44]:
df['Airline'] = df['Airline'].str.extract('([a-zA-Z\s]+)', expand=False).str.strip()
df
Out[44]:
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列,数据被以列表的形式录入,但是我们希望每个数字被录入成单独一列,delay_1, delay_2, ...没有的用NAN替代。

In [45]:
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
Out[45]:
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))的组合作为系列随机值的层次化索引

In [46]:
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
Out[46]:
A  0    0.950249
   1    0.726566
   2    0.495760
   3    0.905605
B  0    0.004121
   1    0.626741
   2    0.121265
   3    0.241187
C  0    0.595867
   1    0.840930
   2    0.102324
   3    0.354690
dtype: float64

43.检查s是否是字典顺序排序的

In [47]:
s.index.is_lexsorted()
# 方法二
# s.index.lexsort_depth == s.index.nlevels
Out[47]:
True

44.选择二级索引为1, 3的行

In [48]:
s.loc[:, [1, 3]]
Out[48]:
A  1    0.726566
   3    0.905605
B  1    0.626741
   3    0.241187
C  1    0.840930
   3    0.354690
dtype: float64

45.对s进行切片操作,取一级索引从头至B,二级索引从2开始到最后

In [49]:
s.loc[pd.IndexSlice[:'B', 2:]]
# 方法二
# s.loc[slice(None, 'B'), slice(2, None)]
Out[49]:
A  2    0.495760
   3    0.905605
B  2    0.121265
   3    0.241187
dtype: float64

46.计算每个一级索引的和(A, B, C每一个的和)

In [50]:
s.sum(level=0)
#方法二
#s.unstack().sum(axis=0)
Out[50]:
A    3.078180
B    0.993314
C    1.893810
dtype: float64

47.交换索引等级,新的Series是字典顺序吗?不是的话请排序

In [51]:
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.950249
1  A    0.726566
2  A    0.495760
3  A    0.905605
0  B    0.004121
1  B    0.626741
2  B    0.121265
3  B    0.241187
0  C    0.595867
1  C    0.840930
2  C    0.102324
3  C    0.354690
dtype: float64
False
0  A    0.950249
   B    0.004121
   C    0.595867
1  A    0.726566
   B    0.626741
   C    0.840930
2  A    0.495760
   B    0.121265
   C    0.102324
3  A    0.905605
   B    0.241187
   C    0.354690
dtype: float64

可视化

In [52]:
import matplotlib.pyplot as plt
df = pd.DataFrame({"xs":[1,5,2,8,1], "ys":[4,2,1,9,6]})
plt.style.use('ggplot')

48.画出df的散点图

In [53]:
df.plot.scatter("xs", "ys", color = "black", marker = "x")
Out[53]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f3d38ea12b0>

49.可视化指定4维DataFrame

In [54]:
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)
Out[54]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f3d36b774a8>

50.在同一个图中可视化2组数据,共用X轴,但y轴不同

In [55]:
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));