将DataFrame变量名作为字符串传递



我有以下函数来绘制图形:

def plot_ATD(DataFrame):
#Initialise 225V ATD plot
fig = plt.figure()
ax = fig.add_subplot(111)
#take columns from data set and make to list which is passed to matplotlib to plot a graph
x = DataFrame['Arrival Time (ms)'].tolist()
y = DataFrame['Intensity'].tolist()
line, = ax.plot(x,y, 'r-')
#use numpy to get the max of Intensity, then determine the corresponding arrival time
ymax = np.max(y)
xpos = y.index(ymax)
xmax = x[xpos]
time = xmax
#add an annotation point at the maxima giving the arrival time at this position
# ax.annotate(s=text of annotation, xy=point to annotate, xytext=position to place text
#              arrowprops=dict(facecolor=color of arrow))
ax.annotate(s=xmax, xy=(xmax, ymax), xytext=(xmax+5, ymax+5),
arrowprops=dict(facecolor='orange'),
)
#ax.set_ylim(0,600000)
ax.set_xlim(0,20)
plt.xlabel('Arrival time (ms)')
plt.title(DataFrame.name)
return plt.show()

我正在以下Panda DataFrames上使用它:

V100 = pd.read_csv('Documents/spreadsheets/Data/100V_9z.csv', names=['Arrival Time (ms)', 'Intensity'])
V125 = pd.read_csv('Documents/spreadsheets/Data/125V_9z.csv', names=['Arrival Time (ms)', 'Intensity'])
V150 = pd.read_csv('Documents/spreadsheets/Data/150V_9z.csv', names=['Arrival Time (ms)', 'Intensity'])
V175 = pd.read_csv('Documents/spreadsheets/Data/175V_9z.csv', names=['Arrival Time (ms)', 'Intensity'])
V200 = pd.read_csv('Documents/spreadsheets/Data/200V_9z.csv', names=['Arrival Time (ms)', 'Intensity'])
V225 = pd.read_csv('Documents/spreadsheets/Data/225V_9z.csv', names=['Arrival Time (ms)', 'Intensity'])

我希望图形的标题是DataFrame的名称,即V100、V125等。

我不确定正确的语法或如何做到这一点?请帮忙!

首先,在函数中使用DataFrame作为数据帧的名称不是一个好的做法,因为它是pandas.DataFrame类本身的名称。例如,最好将其更改为df

因此,您可以使用(例如(设置数据帧的名称

V100.name = 'V100'

并对所有数据帧执行此操作。然后在您的函数中调用(新命名的(df.name,以获得您之前分配给数据帧的名称。

更新

要自动设置数据帧名称,只需进行

file_name = 'Documents/spreadsheets/Data/100V_9z.csv'
V100 = pd.read_csv(file_name, names=['Arrival Time (ms)', 'Intensity'])
V100.name = file_name.split('/')[-1].split('_')[0] # 'V100'

这里有一个解决方法:

Vs= [v for v in locals() if v.startswith('V')] 
for v in Vs:
plot(eval(v),title=v)

创建变量时必须使用更干净的方法(因为eval不安全(,例如使用系列(或字典(:

ser=pd.Series()
ser['V100'] = pd.read_csv('Documents/spreadsheets/Data/100V_9z.csv', 
names=['Arrival Time (ms)', 'Intensity'])

将简化工作。

最新更新