我有一个像这样的数据框 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/