简体   繁体   English

绘制没有嵌套 for 循环的 Pandas 数据透视表

[英]plotting a pandas pivot table without nested for loop

I have a pivot table written with this code:我有一个用以下代码编写的数据透视表:

piv = pd.pivot_table(df, index = ['trial_id','cluster', 'orientation'], columns = 'spatial_freq', values = 'firing_rate')

and looks like this:看起来像这样:

在此处输入图片说明

I want to plot the values for each trial/cluster pair.我想绘制每个试验/集群对的值。 I am able to access these values using .get_level_values() and .xs():我可以使用 .get_level_values() 和 .xs() 访问这些值:

trials = piv.index.get_level_values(0).unique()
trial_1 = piv.xs(trials[0])
clusters = trial_1.index.get_level_values(0).unique()
cluster_1 = trial_1.xs(clusters[0])
cluster_1

out:出去:

cluster_1 的输出

I can then run this variable through plt.plot() to get my desired plot.然后我可以通过 plt.plot() 运行这个变量来得到我想要的图。 This works for me because I need to label my plots with the trial id and the cluster number.这对我有用,因为我需要用试验 ID 和簇号标记我的图。 However, with my solution I would need to run a nested for loop and my dataset is very large.但是,使用我的解决方案,我需要运行嵌套的 for 循环,并且我的数据集非常大。 Is there a way to achieve what I need with just the original pivot table using Pandas functions such as .apply()?有没有一种方法可以使用 Pandas 函数(例如 .apply())仅通过原始数据透视表来实现我所需要的?

Thanks in advance!提前致谢!

You just need one loop.你只需要一个循环。 You can use groupby to get the sub dataframes:您可以使用groupby来获取子数据帧:

for name, group in pvt.groupby(level=[0,1]):
    print(f'plotting group {name}') 
    group.plot() # or custom function, use group as a dataframe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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