如何将循环中的多个文件作为一个表(panda)读取,并从每个表中选择一列并将其附加在一起

2024-06-26 00:26:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个数据文件,每个文件有两列。列1在每个文件中具有相同的数据,而列2随每个文件而更改。我想创建一个矩阵或一个表,使这些数据的形式,然后进行其他功能。np.loadtxt会比pandas更容易/更好吗? 列1列2列(文件1)列3列(文件2)…列n列(文件n) 1.1 3 ... 2.3 32 3 4 2 4 5 9 5 2 5

现在我有这个-

for i in range(0,3):
    file = file_name + '%d' %i+'.dat'
    print(file)
    f=open(file, 'r')
    tble = pd.read_table(f, sep='\s+',skiprows= 15, header=None) 
    time=tble[0]
    inten=tble[1]

但是合并、附加似乎不起作用

    tble['inten'] = pd.Series(inten, index=tble.index)

Tags: 文件数据功能pandasforindex数据文件np
1条回答
网友
1楼 · 发布于 2024-06-26 00:26:10

我将提取每个数据帧中的所有数据文件,然后在第二列中进行合并:

tbls = []
for i in range(0,3):
    file = file_name + '%d' %i+'.dat'
    print(file)
    f=open(file, 'r')
    tble = pd.read_table(f, sep='\s+',skiprows= 15, header=None) 
    tbls.append(tble)
df = pd.concat([tbls[0]] + [tble.iloc[:, 1] for tble in tbls[1:]], axis = 1)

相关问题 更多 >