python - 为第一行中的多列插入 0 的逻辑 - Pandas

标签 python pandas

我有一个 df,它可能包含第一行中两列的 nan 值。如果为真,我想用 0 替换这些值。但是,如果那里有整数,则保持原样。所以这个 df 应该用 0 替换 X,Y

df = pd.DataFrame({   
    'Code1' : ['A','A','B','B','C','C'],    
    'Code2' : [np.nan,np.nan,5,np.nan,np.nan,10],                      
    'X' : [np.nan,np.nan,1,np.nan,np.nan,3],    
    'Y' : [np.nan,np.nan,2,np.nan,np.nan,4],                                   
    })

1)

if df.loc[0,'X':'Y'] == np.nan:
    df.loc[:0, 'X':'Y'] = 0

2)

if df.loc[[0],['X','Y']].isnull():
    df.loc[:0, 'X':'Y'] = 0
else:
     pass

但是这个例子 df 不应该替换为 0,因为存在整数:

df1 = pd.DataFrame({   
    'Code1' : ['A','A','B','B','C','C'],    
    'Code2' : [np.nan,np.nan,5,np.nan,np.nan,10],                      
    'X' : [5,np.nan,1,np.nan,np.nan,3],    
    'Y' : [6,np.nan,2,np.nan,np.nan,4],                                   
    })

最佳答案

df.loc[0, ['X', 'Y']] = df.loc[0, ['X', 'Y']].fillna(0)
>>>> df
  Code1  Code2    X    Y
0     A    NaN  0.0  0.0
1     A    NaN  NaN  NaN
2     B    5.0  1.0  2.0
3     B    NaN  NaN  NaN
4     C    NaN  NaN  NaN
5     C   10.0  3.0  4.0

关于python - 为第一行中的多列插入 0 的逻辑 - Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58927294/

相关文章:

python - 如何按列分组并将一组的所有值复制到 Pandas 中的一行?

python - 通过给定的 geojson 分割包含 lat/lng 的 pandas DataFrame

python - 如何使用 Python 将点放入数字中?

python - TensorFlow 对象检测 API : classification weights initialization when changing number of classes at training using pre-trained models

python - 在python中移动数组的元素

python - 查找至少一行包含字母的列

python - 在 df 中查找值

python - 查找具有给定排名的所有固定长度的子数组

python - 如何使用 FFmpeg 将 RTMP 流转换为视频文件?

python - Pandas 如何将数组放在单个数据框单元格中?