I have two lists and I want to take item names from the list and use it to a loop. Please see the codes below.
df_compressed_list= ['df_compressed_1','df_compressed_2','df_compressed_3','df_compressed_4','df_compressed_5','df_compressed_6','df_compressed_7','df_compressed_8','df_compressed_9','df_compressed_10','df_compressed_11','df_compressed_12','df_compressed_13','df_compressed_14']
plot_image_list= ['compressed_1','compressed_2','compressed_3','compressed_4','compressed_5','compressed_6','compressed_7','compressed_8','compressed_9','compressed_10','compressed_11','compressed_12','compressed_13','compressed_14']
for i in df_compressed_list:
plt.figure(100,figsize=(10,5))
plt.plot(df_compressed_list[i]['time'], df_compressed_list[i]['voltage'])
for j in plot_image_list:
plt.savefig('images\[plot_image_list][j].PNG')
plt.close()
['time'] and ['voltage'] are columns names of a pandas dataframe.I already created dataframe with respective names. I tried the above code but it doesn't work. There is definitely something wrong with my code but I can't figure out what. It shows
TypeError: list indices must be integers or slices, not str
What I want it to do is, it will take the name one by one from the list and put the name in plt.plot(df_compressed_list[i]['time'], df_compressed_list[i]['voltage'])
and plt.savefig('images\[plot_image_list][j].PNG')
so that it would look like this
plt.plot(df_compressed_1['time'], df_compressed_1['voltage'])
plt.savefig('images\compressed_1.PNG')
CodePudding user response:
In this line you trying to excess a list by using keys.
plt.plot(df_compressed_list[i]['time'], df_compressed_list[i]['voltage'])
Maybe your problem is, that instead of df_compressed_list[i]['time']
you want to excess your dataframe like this PANDAS_DATAFRAME[i]['time']
CodePudding user response:
- Elements of
df_compressed_list
are strings, not dataframes. - Thus, the
i
infor i in df_compressed_list:
, being an element of the list (not an index intodf_compressed_list
!), is a string. - Then,
df_compressed_list[i]
attempts to index the list with this string. - This an error since "list indices must be integers or slices, not str".
You could fix this by replacing for i in df_compressed_list:
by for i, _ in enumerate(df_compressed_list):
, but then there'd be more errors:
- Elements of
df_compressed_list
are strings, not dataframes. - Thus,
df_compressed_list[i]
would be a string. - So,
df_compressed_list[i]['time']
would attempt to index this string with another string,'time'
. - This is also an error because
string indices must be integers
, notstr
ings.