Если вам не нужен модуль csv
, я бы порекомендовал использовать метод numpy
loadtxt
для загрузки ваших файлов, то есть
col_time,col_window = np.loadtxt(fname,delimiter=',').T
Эта единственная строказаботится о первых 8 строках вашего цикла for
.Обратите внимание, что операция транспонирования (.T
) необходима для преобразования исходной формы данных (N
строки по 2
столбцам) в 2
строку по N
форме столбца, которая распаковывается в col_time
и col_window
.Также обратите внимание, что loadtxt
автоматически загружает данные в numpy.array
объекты.
Что касается вашего фактического вопроса, я бы использовал нарезку и маскировку:
trailing_window = col_window[:-1] # "past" values at a given index
leading_window = col_window[1:] # "current values at a given index
decreasing_mask = leading_window < trailing_window
quotient = leading_window[decreasing_mask] / trailing_window[decreasing_mask]
quotient_times = col_time[decreasing_mask]
Тогда quotient_times
может бытьпостроен против quotient
.
В качестве альтернативы можно использовать метод numpy
where
, чтобы получить индексы с маской True
:
trailing_window = col_window[:-1] # "past" values at a given index
leading_window = col_window[1:] # "current values at a given index
decreasing_inds = np.where(leading_window < trailing_window)[0]
quotient = leading_window[decreasing_inds] / trailing_window[decreasing_inds]
quotient_times = col_time[decreasing_inds]
Имейте в видучто весь приведенный выше код все еще выполняется в первом цикле for
, но теперь rt
вычисляется внутри цикла как quotient
.Таким образом, после вычисления quotient_times
для построения (также внутри первого цикла):
# Next line opens a new figure window and then clears it
figure(); clf()
# Updated plotting call with the syntax from the answer
plt.plot(quotient_times,quotient,'.',ms=4,label=protname,alpha=0.1)
plt.ylim(0, 1.0001)
plt.xlim(0, 0.003)
plt.title(protname)
plt.xlabel("time")
plt.ylabel("quotient")
plt.legend()
# You may not need this `plt.show()` line
plt.show()
# To save the figure, one option would be the following:
# plt.savefig(protname+'.png')
Обратите внимание, что вам может потребоваться вывести строку plt.show()
из цикла.
Помещениеэто вместе для вас,
import numpy as np
import matplotlib.pyplot as plt
protocols = {}
types = {"data1": "data1.csv", "data2": "data2.csv", "data3": "data3.csv"}
for protname, fname in types.items():
col_time,col_window = np.loadtxt(fname,delimiter=',').T
trailing_window = col_window[:-1] # "past" values at a given index
leading_window = col_window[1:] # "current values at a given index
decreasing_inds = np.where(leading_window < trailing_window)[0]
quotient = leading_window[decreasing_inds] /
trailing_window[decreasing_inds]
quotient_times = col_time[decreasing_inds]
# Still save the values in case computation needs to happen later
# in the script
protocols[protname] = {
"col_time": col_time,
"col_window": col_window,
"quotient_times": quotient_times,
"quotient": quotient,
}
# Next line opens a new figure window and then clears it
plt.figure(); plt.clf()
plt.plot(quotient_times,quotient, ".", markersize=4, label=protname, alpha=0.1)
plt.ylim(0, 1.0001)
plt.xlim(0, 0.003)
plt.title(protname)
plt.xlabel("time")
plt.ylabel("quotient")
plt.legend()
# To save the figure, one option would be the following:
# plt.savefig(protname+'.png')
# This may still be unnecessary, especially if called as a script
# (just save the plots to `png`).
plt.show()