我有一个表:
a b c
1 11 21
2 12 22
3 3 3
NaN 14 24
NaN 15 NaN
4 4 4
5 15 25
6 6 6
7 17 27
我想删除列a
中最后一行之前的所有行,该行的值为null。我想要的输出是:
a b c
NaN 15 NaN
4 4 4
5 15 25
6 6 6
7 17 27
除了first_valid_index
和last_valid_index
,我找不到更好的解决方案。我想我不需要那个。
奖金
如果一行中的所有值都相同,我还想在数据帧中添加一个新列。下列行应具有相同的值:
new a b c
NaN NaN 15 NaN
4 4 4 4
4 5 15 25
6 6 6 6
6 7 17 27
谢谢!
将isna
与idxmax
:一起使用
new_df = df.iloc[df["a"].isna().idxmax()+1:]
输出:
a b c
4 NaN 15 NaN
5 4.0 4 4.0
6 5.0 15 25.0
7 6.0 6 6.0
8 7.0 17 27.0
然后使用pandas.Series.where
和nunique
:
new_df["new"] = new_df["a"].where(new_df.nunique(axis=1).eq(1)).ffill()
print(new_df)
最终输出:
a b c new
4 NaN 15 NaN NaN
5 4.0 4 4.0 4.0
6 5.0 15 25.0 4.0
7 6.0 6 6.0 6.0
8 7.0 17 27.0 6.0
查找包含NaN
:的行
nanrows = df['a'].isnull()
找到最后一个的索引:
nanmax = df[nanrows].index.max()
做切片:
df.iloc[nanmax:]
# a b c
#4 NaN 15 NaN
#5 4.0 4 4.0
#6 5.0 15 25.0
#7 6.0 6 6.0
#8 7.0 17 27.0