【问题标题】:Insert column specific NaN and drop rows depending on value根据值插入特定于列的 NaN 并删除行
【发布时间】:2016-06-15 05:01:44
【问题描述】:

我已经对昆虫进行了几次假设测试。我想删除 result_1 值“小于 10” 的行,我认为这并不重要,但希望将 NaN 的值保留为 单行显示进行了哪些测试以及针对哪种昆虫。

from pandas import Series, DataFrame
import numpy as np

A = Series(['A','A','B','B','B','C'])
B = Series(['ant','flea','flea','spider','spider','flea'])
C = Series([88,77,1,3,2,67])
D = Series(np.random.randn(6))

df = DataFrame({'test':A.values,'insect':B.values,
            'result_1':C.values,'result_2':D.values},
           columns=['test','insect','result_1','result_2'])
df

原来的Dataframe是这样的:

而且因为索引 2,3 和 4 的 results_1 值 both 中有 NaN strong> results columns) 以显示测试 B 是在跳蚤 (index2) 上执行的,应该留下一行以表明测试 B 确实是在蜘蛛上执行的(索引 3 和 4,需要删除一个并且其他需要在结果列中插入 NaN)。

因此,生成的 Dataframe 应如下所示:

【问题讨论】:

    标签: python pandas dataframe insert nan


    【解决方案1】:

    我认为你可以使用:

    #add NaN by condition
    df.loc[df.result_1 < 10, ['result_1','result_2']] = np.nan 
    #drop duplicated by column insect
    df[df.result_1.isnull()] = df[df.result_1.isnull()].drop_duplicates(subset='insect')
    df = df.dropna(how='all')
    print (df)
      test  insect  result_1  result_2
    0    A     ant      88.0 -0.037844
    1    A    flea      77.0 -1.088879
    2    B    flea       NaN       NaN
    3    B  spider       NaN       NaN
    5    C    flea      67.0  1.455632
    

    另一种解决方案是找到相关索引,然后使用 drop 行与此 index

    mask = df.result_1 < 10
    
    df.loc[mask, ['result_1','result_2']] = np.nan 
    a = df[mask].duplicated(subset='insect')
    print (a)
    2    False
    3    False
    4     True
    dtype: bool
    
    a = a[a].index
    df = df.drop(a)
    print (df)
      test  insect  result_1  result_2
    0    A     ant      88.0 -0.176274
    1    A    flea      77.0 -0.123691
    2    B    flea       NaN       NaN
    3    B  spider       NaN       NaN
    5    C    flea      67.0 -0.310655
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多