【发布时间】:2021-04-28 09:25:06
【问题描述】:
下面的数据框按列a 排序,脚本检查列b 的第一行30% 是否为NaN。如果是,and 其余行不都是NaN,那么我们打印True。如果我想检查最后一行是否是NaN 而不是第一行,那么我设置beginning_data=False。我想知道是否有更好的 Pythonic 方式来完成此任务,而不使用 if/else?
import pandas as pd
df = pd.DataFrame({'a' : [1,2,3,4,5,6,7,8,9,10], 'b' : [pd.NA,pd.NA,pd.NA,8,5,6,7,8,1,2]})
pct_rows = 0.3
nr_rows = int(df.shape[0] * pct_rows)
beginning_data = True
if beginning_data:
pct_rows_null = df['b'].iloc[:nr_rows].isna().all()
rest_rows = df['b'].iloc[nr_rows:].notna().all()
else:
pct_rows_null = df['b'].iloc[-nr_rows:].isna().all()
rest_rows = df['b'].iloc[:-nr_rows].notna().all()
print((pct_rows_null & rest_rows))
【问题讨论】:
-
只是一个小问题,但我会将 iloc 更改为
head(nr_rows)和tail(nr_rows) -
这也可能对codereview.stackexchange.com有好处