我有一堆具有完全相同结构的txt文件。每个txt文件包含m行和n列数据。我想对每个条目进行平均并报告最终的df。
txt1
Hour | X1 | X2 | X3 | X4
0 | 15 | 13 | 25 | 37
1 | 26 | 52 | 21 | 45
2 | 18 | 45 | 45 | 25
3 | 65 | 38 | 98 | 14
txt2
Hour | X1 | X2 | X3 | X4
0 | 10 | 13 | 45 | 37
1 | 20 | 53 | 31 | 45
2 | 13 | 43 | 45 | 25
3 | 65 | 32 | 38 | 14
txt3
Hour | X1 | X2 | X3 | X4
0 | 11 | 13 | 25 | 37
1 | 21 | 52 | 21 | 45
2 | 18 | 41 | 45 | 25
3 | 65 | 31 | 98 | 14
最终数据框
Hour | X1 | X2 | X3 | X4
0 | (15+10+11)/3 | .. | 37
1 | (26+20+21)/3 | .. | 45
2 | (18+13+18)/3 | .. | 25
3 | (65+65+65)/3 | .. | 14
什么是有效的方法?
答案 0 :(得分:1)
尝试
void deletea(int x)
{
int q=0,r;
while(list[q].next!=-1 && list[q].info != x)
q = list[q].next ;
r = list[q].next ;
list[q].next = list[r].next ;
list[r].next = avail ;
avail = r;
}
void display()
{
int p = 0;
while(list[p].next != -1)
{
printf("\n%d\t%d\t%d",p,list[p].info,list[p].next) ;
p = list[p].next ;
}
printf("\n%d\t%d\t%d",p,list[p].info,list[p].next) ;
}
如果您有任意数量的DataFrame,则可以
df1 = pd.read_csv('path/to/file_1.txt', sep='|', index_col=0)
df2 = pd.read_csv('path/to/file_2.txt', sep='|', index_col=0)
df3 = pd.read_csv('path/to/file_3.txt', sep='|', index_col=0)
df_avg = (df1 + df2 + df3) / 3
答案 1 :(得分:1)
如果您使用numpy进行读取,则速度可能会更快:
import numpy as np
import re
import pandas as pd
fnames = ['data1.txt', 'data2.txt', 'data3.txt']
mean = 0
for fname in fnames:
mean += np.loadtxt(fname, delimiter='|', skiprows=1)[:, 1:]
mean /= len(fnames)
print(mean)
# or if you want access to all of them:
frames = []
for fname in fnames:
frames.append(np.loadtxt(fname, delimiter='|', skiprows=1)[:, 1:])
frames = np.stack(frames)
mean = np.mean(frames, axis=0)
print(frames)
print(mean)
df = pd.read_csv('data1.txt', sep='|', index_col=0)
df.loc[:, df.columns[:]] = mean
print(df)
然后,只需使用数组创建一个数据框
答案 2 :(得分:1)
以下代码可让您遍历文件夹并将所有文本文件附加到单个数据框中。
import os
import glob
import pandas as pd
os.chdir('C:\\path_to_folder_for_text_files\\')
Filelist = glob.glob('*.txt')
appended_data = []
for file in FileList:
df = pd.read_csv(file,sep='|')
#df = any other operations in each file if required
appended_data.append(df)
appended_data = pd.concat(appended_data)
df = pd.DataFrame(appended_data)
具有附加数据后,请执行以下操作:
df.groupby('Hour')[df.columns[1:]].mean().reset_index()
Hour X1 X2 X3 X4
0 0 12.00 13.00 31.67 37.00
1 1 22.33 52.33 24.33 45.00
2 2 16.33 43.00 45.00 25.00
3 3 65.00 33.67 78.00 14.00