鍍金池/ 問答/數(shù)據(jù)分析&挖掘  Python  數(shù)據(jù)庫/ python中module 'pandas.util.testing' has

python中module 'pandas.util.testing' has no attribute 'choice'

問題背景
書上的一個例子

import pandas.util.testing as tm

colors = tm.choice(['red','green'],size=10)

運行結(jié)果:
圖片描述

但我運行就報錯:

module 'pandas.util.testing' has no attribute 'choice'

我查了一下pandas.util.testing包里面好像的確沒有choice()函數(shù)。。我也不知道當(dāng)初書上那個是怎么做出來的。我看官方好像提供了一個函數(shù)randu_array(),但我用

colors = tm.randu_array(['red','green'],size=10)

報錯:

cannot perform reduce with flexible type

報了一長串的錯,只是最后一句,


問題更新
底下的二樓大佬回復(fù)我說可以這樣

import numpy as np
import pandas.util.testing as tm
tm.np.random.choice()

我試了一下可以!而且我是知道numpy.random里面有個choice()函數(shù)的,
不過為什么tm可以引用到np這個名稱?

回答
編輯回答
疚幼

什么破書……那個 choice 沒定義在那里,所以新版本不小心就沒了吧……

>>> from numpy.random import choice
>>> choice(['red', 'green'])
'red'
2017年7月13日 20:25
編輯回答
法克魷
>>> tm.np.random.choice(['red','green'], 10)
array(['red', 'red', 'red', 'green', 'green', 'red', 'green', 'green',
       'green', 'green'], 
      dtype='<U5')

為什么tm可以引用到np這個名稱?

testing 只是把一些常用的功能集中到一塊而已~
它原來的choice()就是 numpy.random里面的choice()
你可以去看testing的源文件,它導(dǎo)入numpy ,所以可以引用到np這個名稱

2018年2月25日 21:57