用其他列填充NaN和空值

时间:2018-05-23 17:06:28

标签: python pandas dataframe mask

我想用其他列值填充NaN和空值,在这种情况下,由列 @php $like_count = 0; $dislike_count = 0; @endphp @foreach ($post->likes as $like) @php if($like->like == 1) { $like_count++; } if($like->like == 0) { $dislike_count++; } @endphp @endforeach <button type="button" class="btn btn-success">Like <i class="fa fa- thumbs-up"></i><b> {{ $like_count }} </b> </button> <button type="button" class="btn btn-danger">Dislike <i class="fa fa- thumbs-down"></i> <b> {{ $dislike_count }} </b> </button> 填充的列barcode_y

这是我的数据

barcode_x

这就是我需要的东西

    id      barcode_x     barcode_y A   B
0   7068    38927887      38927895  0   12
1   7068    38927895      38927895  0   1
2   7068    39111141      38927895  0   4
3   7116    73094237                18  309
4   7154    37645215      37645215  0   9
5   7342    86972909           NaN  7   25

我猜怎么做?

4 个答案:

答案 0 :(得分:4)

使用mask

x, y = df['barcode_x'], df['barcode_y']
y.mask(y.eq('') | y.isna(), x)

0    38927895
1    38927895
2    38927895
3    73094237
4    37645215
5    86972909
Name: barcode_y, dtype: object

答案 1 :(得分:0)

我建议屏蔽来完成你想要的东西:

df['barcode_y'][df['barcode_y'].isna()] = df['barcode_x'][df['barcode_y'].isna()]

这将普遍适用,不依赖于列是否以某种方式排序,例如barcode_ybarcode_x之前还是之后。

答案 2 :(得分:0)

我在这种情况下使用combine_first ...特别是如果barcode_y不是dtype object

df.barcode_y.combine_first(df.barcode_x)

如果barcode_ydtype object,我认为您可以采取以下额外步骤:

>>> df
   barcode_x barcode_y
0          1         0
1        123      None
2        543
>>> df.barcode_y = df.barcode_y.combine_first(df.barcode_x)
>>> df
   barcode_x barcode_y
0          1         0
1        123       123
2        543
>>> df.loc[df.barcode_y.str.strip()=='', 'barcode_y'] = df.loc[df.barcode_y.str.strip()=='', 'barcode_x']
>>> df
   barcode_x  barcode_y
0          1          0
1        123        123
2        543        543

答案 3 :(得分:-1)

试试这个,

def fillValues(x):    
   x = x['barcode_x'] if np.isnan(x['barcode_y']) else x['barcode_y']
   return x

df["barcode_y"] = df.apply(lambda x : fillValues(x),axis=1)
print(df)
相关问题