简体   繁体   中英

Why this Python "loop code" does not work?

Why this code does not work?

ffi5_1 = pd.read_csv('/Users/d/bm_ffi5_1.csv')
ffi5_2 = pd.read_csv('/Users/d/bm_ffi5_2.csv')
ffi5_3 = pd.read_csv('/Users/d/bm_ffi5_3.csv')
ffi5_4 = pd.read_csv('/Users/d/bm_ffi5_4.csv')
ffi5_5 = pd.read_csv('/Users/d/bm_ffi5_5.csv')

s_list = list(range(1,6))

for x in s_list:
    ffi5_x.jdate = pd.to_datetime(ffi5_x.jdate)

Here jdate is the column of dataframe.

Your code probably fails with a message that you attempt to refer to a non-existing variable ffi5_x .

In order to replace x in the DataFrame name with the current value of x - loop control variable (in 2 places), change your loop to:

for x in s_list:
    exec('ffi5_' + str(x) + '.jdate = pd.to_datetime(ffi5_' + str(x) + '.jdate)')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM