作者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://webptt.com/cn.aspx?n=bbs/Python/M.1625301474.A.622.html
1F:推 MAGICXX: 这是缩排错误吧 要不要检查一下那边有多( 07/03 17:23
2F:→ MAGICXX: 还是真的排错了 07/03 17:23
3F:推 lycantrope: 不是缩排吧,你用df format出来的string就不会是df 07/03 23:36
4F:→ lycantrope: format後的string用exec会出现缩排错误 07/03 23:36
※ 编辑: aovo (123.194.129.138 台湾), 07/04/2021 12:19:54
5F:→ aovo: 感谢指教,我再试试 07/04 19:46