亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

python 如何讓時間識別定義的輸入

python 如何讓時間識別定義的輸入

牛魔王的故事 2021-10-10 13:35:15
我有一個 df 定義,我正在成功地運行操作。我想計算迭代for循環和矢量化操作之間的差異。我已經閱讀了有關如何使用 timeit 的各種示例,但是當我嘗試使用它們時,出現以下錯誤。我究竟做錯了什么?進口:import h5pyimport pandas as pdimport timeit這個循環有效:for u in df['owner'].unique():    print(u, ': ', len(df[(df['owner'] == u)]), sep = '')但是當我嘗試這樣計時時......:s = """\for u in df['owner'].unique():    print(u, ': ', len(df[(df['owner'] == u)]), sep = '')"""time_iter_1_1_1 = timeit.timeit(s)...它產生這個錯誤:---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)<ipython-input-34-7526e96d565c> in <module>()      3 #     print(u, ': ', len(df[(df['owner'] == u)]), sep = '')""")      4 ----> 5 time_iter_1_1_1 = timeit.timeit(s)~\Anaconda2\envs\py36\lib\timeit.py in timeit(stmt, setup, timer, number, globals)    231            number=default_number, globals=None):    232     """Convenience function to create Timer object and call timeit method."""--> 233     return Timer(stmt, setup, timer, globals).timeit(number)    234     235 def repeat(stmt="pass", setup="pass", timer=default_timer,~\Anaconda2\envs\py36\lib\timeit.py in timeit(self, number)    176         gc.disable()    177         try:--> 178             timing = self.inner(it, self.timer)    179         finally:    180             if gcold:~\Anaconda2\envs\py36\lib\timeit.py in inner(_it, _timer)NameError: name 'df' is not defined當我嘗試這個時......:time_iter_1_1_1 = timeit.timeit("""for u in df['owner'].unique():    print(u, ': ', len(df[(df['owner'] == u)]), sep = '')""")...我收到此錯誤:ERROR:root:An unexpected error occurred while tokenizing inputThe following traceback may be corrupted or invalidThe error message is: ('EOF in multi-line string', (1, 57))...NameError: name 'df' is not defineddf 已定義并正常工作。我怎樣才能解決這個問題?
查看完整描述

1 回答

?
Helenr

TA貢獻1780條經驗 獲得超4個贊

有兩種選擇,要么


傳遞一個globals允許timeit解析名稱的參數,

df = pd.DataFrame(...)

timeit.timeit(statement, globals={'df': df}) # globals=globals()

...或者,傳遞一個為您setup設置的字符串參數df。

timeit.timeit(statement, setup='import pandas as pd; df = pd.DataFrame(...)')


查看完整回答
反對 回復 2021-10-10
  • 1 回答
  • 0 關注
  • 251 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號