【问题标题】:Dataframe append entire column if the header row is empty如果标题行为空,则数据框附加整列
【发布时间】:2019-12-16 10:46:08
【问题描述】:

如果标题列为空,我需要将其与附近的列合并。

对于场景 1, 我需要合并第 3 列(金额)和第 4 列(空)。

我需要以下结果。

对于场景 2, 我需要合并第 3 列(空)和第 4 列(金额)。

我需要以下结果。

任何帮助将不胜感激。

注意: 行标题是动态名称。它不是上面提到的静态名称。即,标题名称可以是任何东西。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    例子

       Amount Empty
    0      10     €
    1      20     €
    2      30     €
    3      40     €
    

    使用np.where

    df['Amount'] = np.where(df['Amount'].astype(str) == '€', df['Amount'].astype(str) + ' ' + df['Empty'].astype(str), df['Empty'].astype(str) + ' ' +  df['Amount'].astype(str))
    
    df.drop('Empty',1,inplace=True)
    

      Amount
    0   € 10
    1   € 20
    2   € 30
    3   € 40
    

    【讨论】:

    • 请检查我更新的问题。行标题是动态的。如上所述,它不是静态的。
    • 标题是如何生成的...?请解释一下“动态”
    【解决方案2】:

    用途:

    df = pd.DataFrame({'' : ['€','€','€','€'],
                      'col0' : [50,100,25,90],
                      'col':1,
                      " ": [50, 100, 25, 90], 
                      "col2": ["€", "€", "€", "€"]}).rename(columns={' ':''})
    
    print (df)
          col0  col      col2
    0  €    50    1   50    €
    1  €   100    1  100    €
    2  €    25    1   25    €
    3  €    90    1   90    €
    

    您可以检查数据类型:

    s = df.dtypes
    print (s)
            object
    col0     int64
    col      int64
             int64
    col2    object
    dtype: object
    

    如果列名是空字符串并且 dtype 是对象,则表示列由货币填充,然后逻辑将这些空字符串替换为缺失值并前向填充它们,最后用数字替换空列名并通过回填替换列名:

    m = (s == object) & (s.index == '')
    a = s.index.to_series().mask(m).ffill().replace({'':np.nan}).bfill()
    

    货币和下一个数字列的输出是相同的列名称:

    df.columns = a
    print (df)
       col0  col0  col col2 col2
    0     €    50    1   50    €
    1     €   100    1  100    €
    2     €    25    1   25    €
    3     €    90    1   90    €
    

    然后使用自定义 lambda 函数和 groupby 将其连接在一起:

    def f(x):
        if len(x.columns) == 2:
            if isinstance(x.iloc[0, 0], str):
                return x.iloc[:, 0] + ' ' + x.iloc[:, 1].astype(str)
            else:
                return x.iloc[:, 1] + ' ' + x.iloc[:, 0].astype(str)
        else:
            return x.iloc[:, 0]
    
    df = df.groupby(df.columns, axis=1).apply(f)
    print (df)
    
       col   col0   col2
    0    1   € 50   € 50
    1    1  € 100  € 100
    2    1   € 25   € 25
    3    1   € 90   € 90
    

    【讨论】:

      猜你喜欢
      • 2016-05-31
      • 2021-02-25
      • 2021-08-06
      • 2015-02-23
      • 2019-04-29
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 2016-03-20
      相关资源
      最近更新 更多