解析多个文件并创建单个数据框的更好方法

Better way to parse multiple files and create a single dataframe

我想:

  1. 将文件读入数据帧
  2. 做一些数据操作等
  3. 从数据框中复制一列
  4. 将该列附加到第二个数据框
  5. 重复 1-4 直到读取所有文件

我的实现是:

all_data = [[]]  #list to store each set of values


for i in file_list:
    filepath =  path + i
    df=pd.read_csv(filepath,sep='\t',header=None,names=colsList)
    #various data manipulation, melt, etc, etc, etc.
    all_data.append(df['value'])

df_all = pd.DataFrame(all_data)  
df_all=df_all.T  #Transpose
df_all.set_axis(name_list, axis=1, inplace=True)  #fix the column names

如何更好地实施?

问题:

提前致谢...

如果您将数据保存在 dictionary 中,那么您将得到列。

但每一列都需要唯一名称 - 即 col1col2 等。

import pandas as pd

all_data = {}

all_data['col1'] = [1,2,3]
all_data['col2'] = [4,5,6]
all_data['col3'] = [7,8,9]

new_df = pd.DataFrame(all_data)

print(new_df)

结果:

   col1  col2  col3
0     1     4     7
1     2     5     8
2     3     6     9

for-loop

我只使用 io.StringIO 来模拟内存中的文件 - 但您应该直接使用文件路径。

import pandas as pd
import io

file_data = {
    'file1.csv': '1\t101\n2\t102\n3\t103',
    'file2.csv': '4\t201\n5\t202\n6\t202',
    'file3.csv': '7\t301\n8\t301\n9\t201',
}

file_list = [
    'file1.csv',
    'file2.csv',
    'file3.csv',
]

# ---

all_data = {}

for number, i in enumerate(file_list, 1):
    df = pd.read_csv( io.StringIO(file_data[i]), sep='\t', header=None, names=['value', 'other'] )
    all_data[f'col{number}'] = df['value']

new_df = pd.DataFrame(all_data)

print(new_df)

也可以直接赋新列

new_df[f'column1'] = old_df['value']

import pandas as pd
import io

file_data = {
    'file1.csv': '1\t101\n2\t102\n3\t103',
    'file2.csv': '4\t201\n5\t202\n6\t202',
    'file3.csv': '7\t301\n8\t301\n9\t201',
}

file_list = [
    'file1.csv',
    'file2.csv',
    'file3.csv',
]

# ---

new_df = pd.DataFrame()

for number, i in enumerate(file_list, 1):
    df = pd.read_csv( io.StringIO(file_data[i]), sep='\t', header=None, names=['value', 'other'] )
    new_df[f'col{number}'] = df['value']

print(new_df)