python - 循环遍历 pandas 数据框行以应用条件的替代方案?

标签 python pandas numpy

我有一个数据框,我想根据某些条件进行修改。实际的数据框比下面的示例大得多(35k 行,400 列),并且有更多的患者列。

如果在患者列下给定行有 2 个 NaN,我想删除整行。接下来,我想在数据帧中附加一列,其中包含每行所有患者值的 df.std() 。我读到不建议迭代 pandas 数据框,但我很难使用 numpy 来实现此目的。

输入:

In [1]: df=pd.DataFrame({'chromosome':[1,1,5,4], 
   ...:                  'strand':['-','-','+','-'], 
   ...:                  'elementloc':[4991, 8870, 2703, 9674], 
   ...:                  'Patient1_Psi': ['NaN', 0.25,0.63,0.92], 
   ...:                  'Patient2_Psi':[0.11, 0.45, 'NaN', 1.0], 
   ...:                  'Patient3_Psi':['NaN', 0.1, 'NaN', 0.4]}) 
   ...: df  

                                                                

Out[2]: 
   chromosome strand  elementloc Patient1_Psi Patient2_Psi Patient3_Psi
0           1      -        4991          NaN         0.11          NaN
1           1      -        8870         0.25         0.45          0.1
2           5      +        2703         0.63          NaN          NaN
3           4      -        9674         0.92            1          0.4

我想要的输出:

In [3]: df_new=pd.DataFrame({'chromosome':[1,4], 
   ...:                  'strand':['-','-'], 
   ...:                  'elementloc':[ 8870, 9674], 
   ...:                  'Patient1_Psi': [0.25,0.92], 
   ...:                  'Patient2_Psi':[0.45, 1.0], 
   ...:                  'Patient3_Psi':[0.1, 0.4], 
   ...:                   'std':[0.175594, 0.325781]}) 
   ...: df_new                                                                 


Out[4]: 
   chromosome strand  elementloc  Patient1_Psi  Patient2_Psi  Patient3_Psi       std
0           1      -        8870          0.25          0.45           0.1  0.175594
1           4      -        9674          0.92          1.00           0.4  0.325781

建议?

最佳答案

您可以这样做,使用 filter 进行与模式匹配的列过滤:

df = df.replace('NaN', np.nan)
df_new = df[~df.filter(like='Patient').isna().any(axis=1)]
pd.concat([df_new, df_new.filter(like='Patient').std(axis=1).rename('std')], axis=1)

输出:

   chromosome strand  elementloc  Patient1_Psi  Patient2_Psi  Patient3_Psi       std
1           1      -        8870          0.25          0.45           0.1  0.175594
3           4      -        9674          0.92          1.00           0.4  0.325781

关于python - 循环遍历 pandas 数据框行以应用条件的替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63057839/

相关文章:

python - Pandas 提取最高程度的资格基础重要性

python - Pandas :分组和重新索引后在行之间操作

python魔杖错误 "wand.resource.DestroyedResourceError: <wand.image.Image: (closed)> is destroyed already"

python - 无法保存Qt绘图的状态

python - 值错误: time data '10/11/2006 24:00' does not match format '%d/%m/%Y %H:%M'

python - 无法将 3d NumPy 数组 reshape 为 2d NumPy 数组

python - 实例化类、调用其方法之一并从 lambda 函数返回它的 pythonic 方式是什么?

python - 在 pandas 中创建直方图

python - 我什么时候应该使用 hstack/vstack vs append vs concatenate vs column_stack?

Python在Mac上运行matplotlib.nxutilspoints_inside_poly