【问题标题】:How can I filter data from a DataFrame so that those values that are less than a threshold are 0 and the rest are 1 in Python?如何从 DataFrame 中过滤数据,使那些小于阈值的值在 Python 中为 0,其余为 1?
【发布时间】:2020-05-09 22:30:14
【问题描述】:

我从原始 Dataframe 中提取了一个数据子集,看起来像Test Data Frame

并且我要求根据阈值替换数据集值;对于那些小于阈值 = 0.018990814050501657 的条目将等于 0,其余条目将为 1。我尝试了以下代码:

            for i in range(0,3):
                for col in new_data1:
                     if math.isnan(new_data1[col][i])==False:

                          if new_data1[col][i]<threshold:
                             r_1=new_data1[col].replace(new_data1[col][i],0)
                             print(r_1)
                          else:
                             r_2=new_data1[col].replace(new_data1[col][i],1)
                             print(r_2)

但我得到了下一个输出:

Output

我得到的结果或多或少符合我的预期,除了最后两列我没有得到一列作为输出,就好像我得到第一列一样

【问题讨论】:

  • 使用np.where(new_data1[col][i]&lt;threshold, 0, 1)

标签: pandas dataframe filter replace python-3.7


【解决方案1】:

这样的事情应该适用于您正在尝试做的事情:

threshold = .18
new_data = [.18, .01, 3]
bins = [int(r < threshold) for r in new_data]

print(bins)

[0, 1, 0]

【讨论】:

  • 如果要替换,只需将列设置回自身:new_data = bins
【解决方案2】:

重症监护室

import numpy as np
import pandas as pd
df=pd.DataFrame({'ENSG00000000003':[0,np.nan,np.nan],'ENSG00000000419':[0.013031,0.000000,np.nan],'ENSG00000000457':[0.019190,0.019359,np.nan]})

用 0 填充所有 NaN

df.fillna(0, inplace=True)

使用 np.where 对数据框应用阈值

df.apply(lambda x: (np.where(x< 0.018990814050501657,0,x)))

输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-22
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 2018-07-25
    相关资源
    最近更新 更多