如何将多个csv文件的选定列连接到一个数据帧中?朱皮

2024-10-16 20:44:56 发布

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

我有点困惑,因为以下几点似乎有用:

raw_data_df = pd.DataFrame()


temp = pd.read_csv('/Users/bob/desktop/Research_data/tobii/42r-export.csv', sep = ',', encoding = 'latin-1')
raw_data_df['1'] = temp['Gaze point X']
raw_data_df['2'] = temp['Gaze point Y']

但是,以下操作不起作用:

^{pr2}$

文件在哪里

path = "/Users/bob/desktop/Research_data/tobii/"
files = [f for f in listdir(path) if isfile(join(path,f))]

我得到了一个列表列表,而不是返回列名称为i+“x”或i+“y”的pandas数据框。在

下面是一个用原始数据输出的示例

132660     857
132661     846
Name: Gaze point X, Length: 132662, dtype: int64
0      1206
1      1204
2      1205
3      1205

如何将多个csv文件的选定列连接到一个数据帧中?在


Tags: 文件csvpathdfdatarawuserstemp
3条回答

抱歉有个直营店我正在搜索的文件里面的文件把所有的东西都翻出来了。我刚刚删除了它,它正在工作。在

我不认为有任何必要初始化一个空的数据帧。您可以迭代文件,只加载所需的列(使用usecols),然后在末尾连接所有数据帧。在

此外,当连接路径工件时,使用os.path.join。在

import os

cols = ['Gaze point X', 'Gaze point Y']

df_list = []
for f in files:
    temp = pd.read_csv(
         os.path.join(path, f), sep=',', encoding='latin-1', usecols=cols
    )
    temp.columns = [f + i for i in ['x', 'y']]
    df_list.append(temp)

现在,只需用pd.concat连接数据帧。在

^{pr2}$

基于@COLDSPEED's solution,可以使用列表理解:

def rename_cols(df, f):
    df.columns = [f + i for i in ['x', 'y']]
    return df

df = pd.concat([rename_cols(pd.read_csv(os.path.join(path, f),
                sep=',', encoding='latin-1', usecols=cols), f) for f in files],
                ignore_index=True)

相关问题 更多 >