绘制数据框的 Pythonic 方法和具有不同 x 值的 y 值的平均值

Pythonic way to plot data frames AND average of y values with different x values

我有以下 4 个不同的数据帧,它们位于 4 个文件中:

0 P 1 E 1 1
1 P 1 E 1 2
2 P 1 E 2 3
3 P 1 E 3 4
4 P 1 E 4 5
5 P 1 B 0 6
6 P 1 B 1 7
7 P 1 B 2 8
8 P 1 B 3 9
9 P 1 B 4 10
1 P 1 E 1 3
2 P 1 E 2 4
3 P 1 E 3 5
4 P 1 E 4 6
5 P 1 B 0 7
6 P 1 B 1 8
7 P 1 B 2 9
8 P 1 B 3 10
9 P 1 B 4 11 
10 P 1 B 1 12 
2 P 1 E 1 5
3 P 1 E 2 6
4 P 1 E 3 7
5 P 1 E 4 8
6 P 1 B 0 9
7 P 1 B 1 10
8 P 1 B 2 11
9 P 1 B 3 12
10 P 1 B 4 13 
11 P 1 B 1 14 
2 P 1 E 1 5
3 P 1 E 2 6
4 P 1 E 3 7
5 P 1 E 4 8
6 P 1 B 0 9
7 P 1 B 1 10
8 P 1 B 2 11
9 P 1 B 3 12
10 P 1 B 4 13 
11 P 1 B 1 14 

我想绘制 each 数据框的第一列和最后一列(我可以做到),然后绘制最后一列的平均值(我不能做到). 请注意(c.f. 以上数据),我需要具有不同 x 值的 y 值的平均值。 第二个解决方案 ,看起来很有希望,但并没有真正解决我的问题,因为我不想为我的每个数据帧(我有超过 50 个)[=19] 创建一个 (x1,y1) 对=]

我尝试使用 pd.concat 进行连接,但列的名称打印在连接的数据框中。

使用上述答案给出的解决方案

x1 = np.arange(10)
x2 = np.arange(10)+1  
x3 = np.arange(10)+2
x4 = np.arange(10)+3
y1 = x1+1
y2 = x2+2
y3 = x3+3
y4 = x4 +4
df=pd.concat([pd.Series(y1,index=x1),
            pd.Series(y2,index=x2),
            pd.Series(y3,index=x3),
            pd.Series(y4,index=x4)], axis=1).mean(axis=1) 
 ax.plot(x1, y1)
 ax.plot(x2, y2)
 ax.plot(x3, y3) 
 ax.plot(x4, y4) 
 df.plot(color='red')

我正在寻找如下所示的图表:

Felipe Lanza 的以下解决方案是在我编辑此问题之前给出的,其中包含我需要具有不同 x 值的 y 值的平均值的信息。

据我了解,您担心的是处理同名的不同列...

我做了很多假设,但按照这些思路应该可行:

(编辑) FWIW,这是您提出的解决方案的更简单版本:

path =  'path/to/dataFrame'
all_files = glob.glob(path + "/*.csv")
cols_list = []
fig, ax = plt.subplots()

for filename in all_files:
    # You can directly load only the two columns being used...
    df = pd.read_csv(filename, sep=" ", usecols=[0, 5], index_col=0, names=["A", "ID"], header=None)
    # ... and skip the conversion to arrays and concatenating a series
    cols_list.append(df)
    df.plot(ax=ax, style='o-')

cols_list_df = pd.concat(cols_list, axis=1)
cols_list_df.mean(axis=1).plot(ax=ax, style='o-')

使用上面 Felipe Lanza 的回答和 DYZ 的回答 我找到了解决问题的方法:

 path =  'path/to/dataFrame'
 all_files = glob.glob(path + "/*.csv")
 cols_list = []
 fig, axes = plt.subplots()

  for i, filename in enumerate(all_files):
    df = pd.read_csv(filename, sep=" ", names = ["A", "E", "C","O","M","ID"],header=None )
    x=df["A"]        
    y=df["ID"]  
    xarray=np.array(x)
    yarray=np.array(y)
    df2=pd.concat([pd.Series(yarray,index=xarray)],axis=1).mean(axis=1)
    cols_list.append(df2)
    axes.plot(x, y,'o-')
  cols_list_df=pd.concat(cols_list,axis=1)
  cols_list_df.mean(axis=1).plot(style='o-')

使用上面发布的数据框,情节如下所示:

我确定应该有更智能的解决方案,但这对我来说已经足够了。