如果标题行为空,则数据框会追加整列

时间:2019-12-16 10:46:08

标签: python pandas dataframe

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

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

enter image description here

我需要以下结果。

enter image description here

对于方案2, 我需要合并第3栏(空)和第4栏(金额)。

enter image description here

我需要以下结果。

enter image description here

任何帮助将不胜感激。

注意: 行标题是动态名称。如上所述,它不是静态名称。即标题名称可以是任何内容。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

使用:

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    €

您可以检查dtypes:

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