【问题标题】:How can I join selected columns of multiple csv files into one data frame? Jupyter如何将多个 csv 文件的选定列连接到一个数据框中?木星
【发布时间】:2018-02-08 03:18:25
【问题描述】:

我有点困惑,因为以下似乎可行:

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']

但是以下方法不起作用:

for i in files:
  temp = pd.read_csv(path + i , sep = ',', encoding = 'latin-1')
  print(temp['Gaze point X'])
  raw_data_df[i+"x"] = temp['Gaze point X']
  raw_data_df[i+"y"] = temp['Gaze point Y']

文件在哪里

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

我没有返回列名为 i+"x" 或 i+"y" 的 pandas 数据框,而是得到一个列表列表。

这里是 raw_data_df 输出的示例

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

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

【问题讨论】:

  • 什么是列表列表?
  • 我返回数据框,它位于所有列的某种列表中

标签: python pandas jupyter


【解决方案1】:

我认为没有必要初始化一个空数据框。您可以遍历您的文件,仅加载您需要的列(使用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 连接起来。

df = pd.concat(df_list, axis=1)

【讨论】:

    【解决方案2】:

    抱歉,我正在搜索的文件中有一个 ds.store 文件,该文件已完成所有操作。我刚刚删除了它,它正在工作。

    【讨论】:

      【解决方案3】:

      @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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-16
        • 1970-01-01
        • 2017-01-10
        相关资源
        最近更新 更多