python - 将 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()
我在以下 pandas 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'
推荐阅读
- scala - 无法通过火花读取 VCF 文件
- python - 解析 strftime 输出时出现 Python strptime 错误
- c++ - 从文件中读取动态位集写入的数据无法读取正确的数据
- vim - 如何使用 ctags 和 fzf 配置 VIM 代码完成
- pagespeed-insights - 来源摘要或实验室数据?
- vuejs3 - 将 Bootstrap 5 与 Vue 3 一起使用
- reactjs - 将 this.setstate 与 Fetch API 一起使用
- php - PHP DomDocument 获取锚标记href 和内部html?
- javascript - 如何在使用 window.location.replace() 创建重定向路径时防止 XSS?
- javascript - JSON stringify 在整个 json 对象周围添加引号并转义字符