将 0 或 1 的实例计数到系列

Counting instances of 0 or 1 to series

如果我的数据框使用了一个我希望计数的实例值为 0 或 1 的列,那么针对索引迭代标记为 0 或 1 的列的语法是什么。

这个:

output = df.Series([0,1], index= ['no', 'yes'])

将return:

no    0
yes       1
dtype: int64

而我想获得整个列的总体 no/yes 标记计数为 0 或 1。

实际数据框与 scikit-learn 数据相关,我在数据集末尾创建了一个目标列,因此:最差凹点最差对称性最差分形维数目标<br> 0 0.26540 0.4601 0.11890 0.0

正在尝试这样映射:

    status = {0:'Malignant', 1:'Benign'}
    cancerdf['target'] = cancerdf['target'].map(status)

结果

TypeError: tuple indices must be integers or slices, not str

我正在尝试 return 一个系列,但似乎偏离了轨道。

我认为你需要 value_countsrenamemap:

np.random.seed(123)
s = pd.Series(np.random.choice([0,1], size=10))
print (s)
0    0
1    1
2    0
3    0
4    0
5    0
6    0
7    1
8    1
9    0
dtype: int32

d = {0:'No', 1:'yes'}
print (s.value_counts().rename(index=d))
No     7
yes    3
dtype: int64

或者:

d = {0:'No', 1:'yes'}
print (s.map(d).value_counts())
No     7
yes    3
dtype: int64

或者可能需要 map:

np.random.seed(123)
df = pd.DataFrame({'A':np.random.choice([0,1], size=10)})

d = {0:'No', 1:'yes'}
df['A'] = df['A'].map(d)
print (df)
     A
0   No
1  yes
2   No
3   No
4   No
5   No
6   No
7  yes
8  yes
9   No

编辑:

我认为问题是 target 列中的数据 type 不是 int,而是 float.

所以需要:

status = {0:'Malignant', 1:'Benign'}
cancerdf['target'] = cancerdf['target'].astype(int).map(status)

如果它不起作用,有些数据不是数字,解决方案是使用 to_numeric 将它们替换为 NaN,然后将它们转换为一些 int,例如 2 最后转换为 int:

cancerdf = pd.DataFrame(data={'Target':[1,0,1,'d', 'nan', np.nan]})
print (cancerdf)
  Target
0      1
1      0
2      1
3      d
4    nan
5    NaN

status = {0:'Malignant', 1:'Benign'}
cancerdf['Target'] = pd.to_numeric(cancerdf['Target'], errors='coerce') \
                       .fillna(2).astype(int).map(status)

print (cancerdf)
      Target
0     Benign
1  Malignant
2     Benign
3        NaN
4        NaN
5        NaN