python - 在 pandas python 数据框中移动上面的列并删除行

标签 python python-3.x pandas dataframe python-2.7

我有一个像这样的数据框 df

A        B        C        D        E        F        G        H
a.1      b.1     
                  
                  c.1      d.1 
                  c.2      d.2           e.1      f.1 
                                                      

                                                     g.1       h.1
  


创建示例 DataFrame

from io import StringIO

s = """A,B,C,D,E,F,G,H
a.1,b.1,,,,,,
,,c.1,d.1,,,,
,,c.2,d.2,e.1,f.1,,
,,,,,,g.1,h.1"""

df = pd.read_csv(StringIO(s))

我想删除这些额外的空格,并且我希望数据框从顶行开始。谁能帮忙。

我想要的结果是

A        B        C        D        E        F        G        H
a.1      b.1      c.1      d.1      e.1      f.1      g.1       h.1
                  c.2      d.2                                                   

最佳答案

您可以将每列向后移动通过 first_valid_index 找到的前面缺失值的数量:

df.apply(lambda s: s.shift(-s.first_valid_index()))

获取

     A    B    C    D    E    F    G    H
0  a.1  b.1  c.1  d.1  e.1  f.1  g.1  h.1
1  NaN  NaN  c.2  d.2  NaN  NaN  NaN  NaN
2  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN
3  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN

要删除充满 NaN 的行并用空字符串填充其余行:

out = (df.apply(lambda s: s.shift(-s.first_valid_index()))
         .dropna(how="all")
         .fillna(""))

获取

>>> out

     A    B    C    D    E    F    G    H
0  a.1  b.1  c.1  d.1  e.1  f.1  g.1  h.1
1            c.2  d.2

注意:这假设您的索引是0..N-1;因此,如果不是,您可以预先存储它,然后恢复回来:

index = df.index
df = df.reset_index(drop=True)
df = (df.apply(lambda s: s.shift(-s.first_valid_index()))
        .dropna(how="all")
        .fillna(""))
df.index = index[:len(df)]

要使拉取特定于某些列:

def pull_up(s):
    # this will be a column number; `s.name` is the column name
    col_index = df.columns.get_indexer([s.name])

   # for example: if `col_index` is either 7 or 8, pull by 4
   if col_index in (7, 8):
       return s.shift(-4)
   else:
       # otherwise, pull as much
       return s.shift(-s.first_valid_index())

# applying
df.apply(pull_up)

关于python - 在 pandas python 数据框中移动上面的列并删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67910688/

相关文章:

使用科学记数法对变量进行 Python 数学计算

python - 仅使用特定键从字典字典创建数据框

python - login_required 装饰器不起作用,flask-Login 允许匿名用户

python - 使用python解析大(9GB)文件

python-3.x - PyQt5 中的 QWebSettings(版本 5.6.0)

python - 无法将 Epoch 值转换为人类可读的日期格式 python

python - 按值重新格式化 pandas DataFrame 计数

python - 如果它们具有相同的索引,如何 reshape 数据框?

python - 为 Django + Celery + RabbitMQ 预订?

python - matplotlib 在自动生成的 html 中嵌入图形