【问题标题】:Choose first or last rows depending on boolean根据布尔值选择第一行或最后一行
【发布时间】: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))

【问题讨论】:

标签: python pandas slice


【解决方案1】:

我猜你可以在这里使用 np.where ->

pct_rows = 0.3
nr_rows = int(df.shape[0] * pct_rows)

beigining = np.where((df['b'].iloc[:nr_rows].isna().all()) & (df['b'].iloc[nr_rows:].notna().all()),True, False)
end  = np.where((df['b'].iloc[-nr_rows:].isna().all()) & (df['b'].iloc[:-nr_rows].notna().all()),True, False)

输出-

print(beigining,end) # True False

通过 np.select -


pct_rows = 0.3
nr_rows = int(df.shape[0] * pct_rows)

condlist = [
    (df['b'].iloc[:nr_rows].isna().all()) & (df['b'].iloc[nr_rows:].notna().all()),
    (df['b'].iloc[-nr_rows:].isna().all()) & (df['b'].iloc[:-nr_rows].notna().all())
]
choiselist = [
    'True',
    'False'
]
np.select(condlist,choiselist)

我猜你想要这个(如果两个条件都为真,则返回真,否则为假)->

cond1 = (df['b'].iloc[:nr_rows].isna().all()) & (df['b'].iloc[nr_rows:].notna().all())
cond2 = (df['b'].iloc[-nr_rows:].isna().all()) & (df['b'].iloc[:-nr_rows].notna().all())
np.where((cond1 & cond2), True, False)

【讨论】:

  • 嘿!我只想要 true 或 false,而不是 true 和 false 作为输出。在使用 select 之前你有一个答案,这似乎是我想要的
  • 谢谢!我可能会使用带有np.select(condlist, choice) 的那个,我可以在其中放置choice = [beginning, ~beginning]。因为我只想要基于布尔值beginning 的条件之一
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-10
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多