【问题标题】:Pandas append data frames, add a field, and then flood the field with a default value?Pandas 附加数据帧,添加一个字段,然后用默认值填充该字段?
【发布时间】:2013-01-19 16:15:57
【问题描述】:

我有几个包含所有相同列名的数据框。我想将它们附加到主数据框中。我还想创建一个表示原始字段的列,然后用原始数据框名称填充它。我有一些有效的代码。

df_combine = df_breakfast.copy()
df_combine['X_ORIG_DF'] = 'Breakfast'
df_combine = df_combine.append(df_lunch, ignore_index=True)
df_combine['X_ORIG_DF'] = df_combine['X_ORIG_DF'].fillna('Lunch')
# Rinse and repeat

但是,它似乎不优雅。我希望有人可以为我指出一个更优雅的解决方案。提前感谢您的宝贵时间!

注意:已编辑以反映评论!

【问题讨论】:

  • 注意:您的第一行被第二行覆盖,第三行更改 df_breakfast,这可能会也可能不会接受...
  • 第一行是复制错误,但第二行是真正的错误!谢谢你的收获!

标签: python pandas


【解决方案1】:

我肯定会考虑以一种可以简洁地访问名称而不是作为变量名称的方式来重构您的数据(如果它们必须在开始时是分开的)。
例如字典:

d = {'breakfast': df_breakfast, 'lunch': df_lunch}

创建一个函数,为每个 DataFrame 赋予一个新列:

def add_col(df, col_name, col_entry):
    df = df.copy() # so as not to change df_lunch etc.
    df[col_name] = col_entry
    return df

并将每个 DataFrame 列表与附加列 ('X_ORIG_DF') 结合起来:

In [3]: df_combine = pd.DataFrame().append(list(add_col(v, 'X_ORIG_DF', k)
                                           for k, v in d.items()))
Out[3]: 
   0  1  X_ORIG_DF
0  1  2      lunch
1  3  4      lunch
0  1  2  breakfast
1  3  4  breakfast

在本例中:df_lunch = df_breakfast = pd.DataFrame([[1, 2], [3, 4]])

【讨论】:

    【解决方案2】:

    在尝试将多个文件组合在一起以在主数据框中进行分析时,我遇到了与您类似的问题。这是一种通过独立加载每个数据帧来创建主数据帧的方法,在名为“ID”的列中为每个数据帧提供一个标识符并将它们组合起来。如果您的数据是名为datadir 的目录中的文件列表,我将执行以下操作:

    import os
    import pandas as pd
    
    data_list = os.listdir(datadir)
    df_dict = {}
    
    for data_file in data_list:
        df = read_table(data_file)
        #add an ID column based on the file name.
        #you could use some other naming scheme of course 
        df['ID'] = data_file
        df_dict[data_file] = df
    
    #the concat function is great for combining lots of dfs. 
    #it takes a list of dfs as an argument.
    combined_df_with_named_column = pd.concat(df_dict.values())
    

    【讨论】:

      猜你喜欢
      • 2012-10-28
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多