nunique排除熊猫中的某些值

时间:2019-03-09 06:58:15

标签: python pandas dataframe

我正在按行计算唯一值。但是我想排除值0,然后计算唯一性

<div class="uploadBox whiteBox">
                <h1 class="fontTitle" > Upload Your Photos</h1>
                <hr>
<div class="scroller">


                <div class="uploader boxCorners">
                       <div class="imagePreview boxCorners" id="imagePreview1" style="background-image: url(https://picsum.photos/200/300);">
                       <input type="file" id="imageUpload1">
                       </div>
                </div>


                <div class="uploader boxCorners">
                       <div class="imagePreview boxCorners" id="imagePreview2" style="background-image: url(https://picsum.photos/600/300);">
                       <input type="file" id="imageUpload2">
                       </div>
                </div>
                                <div class="uploader boxCorners">
                       <div class="imagePreview boxCorners" id="imagePreview2" style="background-image: url(https://picsum.photos/600/300);">
                       <input type="file" id="imageUpload2">
                       </div>
                </div>
                                <div class="uploader boxCorners">
                       <div class="imagePreview boxCorners" id="imagePreview2" style="background-image: url(https://picsum.photos/600/300);">
                       <input type="file" id="imageUpload2">
                       </div>
                </div>
                                <div class="uploader boxCorners">
                       <div class="imagePreview boxCorners" id="imagePreview2" style="background-image: url(https://picsum.photos/600/300);">
                       <input type="file" id="imageUpload2">
                       </div>
                </div>
</div>

预期产量

d = {'col1': [1, 2, 3], 'col2': [3, 4, 0], 'col3': [0, 4, 0],}
df = pd.DataFrame(data=d)
df

    col1    col2    col3
0   1       3       0
1   2       4       4
2   3       0       0

col1 col2 col3 uniques 0 1 3 0 2 1 2 4 4 2 2 3 0 0 1 ,其中包括所有值

3 个答案:

答案 0 :(得分:4)

为此,您可以简单地用Nan值替换零。

import pandas as pd
import numpy as np
d = {'col1': [1, 2, 3], 'col2': [3, 4, 0], 'col3': [0, 4, 0]}
df = pd.DataFrame(data=d)
df['uniques'] =  df.replace(0, np.NaN).nunique(axis=1)

答案 1 :(得分:1)

尝试一下:

HttpServletRequest request -> request.getRemotePort()

答案 2 :(得分:1)

不使用replace的简洁版本:

df['unique'] = df[df!=0].nunique(axis=1)
df

输出:

   col1  col2  col3  unique
0     1     3     0       2
1     2     4     4       2
2     3     0     0       1