python - 在python pandas数据框中获取非空最新值

标签 python pandas data-analysis

我想获取所有变量的最新非空值。例如,在此数据集中,我们有 3 个服务日期。

import pandas as pd
df =pd.DataFrame( {'PatientID': [1, 1, 1], 
'Date': ['01/01/2018', '01/15/2018','01/20/2018'],
'Height': ['Null', '178', 'Null'],
'Weight': ['Null', '182', '190'],
'O2 Level': ['95', '99', '92'],
'BPS': ['120', 'Null', 'Null'],
'DPS': ['80', 'Null', 'Null']})

Example Dataset

作为输出,我需要这样的东西:

df = pd.DataFrame( {'PatientID': [1], 
'Height': ['178'],
'Weight': ['190'],
'O2 Level': ['92'],
'BPS': ['120'],
'DPS': ['80']})

Expected Output

我的原始数据集有数千名患者和 100 多个协变量。目前我正在使用三重循环来完成这个任务,这是非常低效的。我正在寻找更有效的解决方案。

最佳答案

我认为您需要先删除列 Date,将 null 替换为 NaN,然后调用 groupbylast :

d = {'PatientID': [1, 1, 1], 
'Date': ['01/01/2018', '01/15/2018','01/20/2018'],
'Height': ['Null', '178', 'Null'],
'Weight': ['Null', '182', '190'],
'O2 Level': ['95', '99', '92'],
'BPS': ['120', 'Null', 'Null'],
'DPS': ['80', 'Null', 'Null']}
c = ['PatientID','Date','Height','Weight','O2 Level','BPS','DPS']
df = pd.DataFrame(d, columns=c)
print (df)
   PatientID        Date Height Weight O2 Level   BPS   DPS
0          1  01/01/2018   Null   Null       95   120    80
1          1  01/15/2018    178    182       99  Null  Null
2          1  01/20/2018   Null    190       92  Null  Null

print (df.drop('Date', 1).replace('Null', np.nan))
   PatientID Height Weight O2 Level  BPS  DPS
0          1    NaN    NaN       95  120   80
1          1    178    182       99  NaN  NaN
2          1    NaN    190       92  NaN  NaN

df = df.drop('Date', 1).replace('Null', np.nan).groupby('PatientID', as_index=False).last()
print (df)
   PatientID Height Weight O2 Level  BPS DPS
0          1    178    190       92  120  80

关于python - 在python pandas数据框中获取非空最新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48729001/

相关文章:

python - 如何解析没有日期的时间字符串和没有时间的日期字符串?

python - 构成 pandas dataframe 单元的数组的最大值

python - 使用 scipy curve_fit 进行猜测

Python Pandas 计算不包括当前组的标准偏差,带有矢量化解决方案

python - 如何根据两列的差异将行添加到数据框

python - Pandas 如何聚合多个列

mysql - 我如何滞后 MySQL 中的列?

java - Python、C/++、java...有没有用于比较音频信号的 api?

python - 如何使用 PUT 在 Django 休息框架中测试文件上传?

python - 在Python(pyrasite)中检查线程中的局部变量?