作者aovo (aovo)
看板Python
標題[問題] 請問exec的用法
時間Sat Jul 3 16:37:52 2021
各位前輩好,我有個沒幾行的function裡面用到exec函式,如下所示,主要是想把input
data裡的資料按照時間切分,生成新的data,不過執行後一直在報錯,想請問各位前輩我
哪裡用錯了,感謝。
==============================================================================
def cut_date(df, column_name, start, end):
for i in range(len(df[column_name])-1):
if df[column_name][i][:4] == str(start-1) and
df[column_name][i+1][:4] == str(start):
x = i
print('index %s: %s' % (x, df[column_name][x]))
for i in range(len(df[column_name])-1):
if df[column_name][i][:4] == str(end) and
df[column_name][i+1][:4] == str(end+1):
y = i
print('index %s: %s' % (y, df[column_name][y]))
exec('{}_mod = {}.iloc[x+1:y+1, :]'.format(df, df))
exec('{}_mod.reset_index(drop=True, inplace=True)'.format(df))
然後我用了下列指令執行 cut_date(df, '時間', 2013, 2016)
錯誤訊息如下
Traceback (most recent call last):
File
"/Users/User/opt/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py",
line 3437, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-30-d5d2e894f930>", line 1, in <module>
cut_date(df, '日期', 2013, 2016)
File "<ipython-input-22-c0e363e719e0>", line 12, in cut_date
exec('{}_mod = {}.iloc[x+1:y+1, :]'.format(df, df))
File "<string>", line 1
日期
^
IndentationError: unexpected indent
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.194.129.138 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1625301474.A.622.html
推 MAGICXX: 這是縮排錯誤吧 要不要檢查一下那邊有多( 07/03 17:23
→ MAGICXX: 還是真的排錯了 07/03 17:23
推 lycantrope: 不是縮排吧,你用df format出來的string就不會是df 07/03 23:36
→ lycantrope: format後的string用exec會出現縮排錯誤 07/03 23:36
※ 編輯: aovo (123.194.129.138 臺灣), 07/04/2021 12:19:54
→ aovo: 感謝指教,我再試試 07/04 19:46