pandas value_counts with bins参数

时间:2018-04-19 10:15:29

标签: python pandas

我有一个像这样的数据框,

col1
1
2
3
2
2
3
1
1
2
3
1
1
3
3
1
1
3

当我计算

print df['col1'].value_counts(bins=2)

它给了我,

(0.997, 2.0]    11
(2.0, 3.0]       6
Name: col1, dtype: int64

结果很好。但在索引中,它会混合使用(]。 为什么它表现得像这样。因为我想将索引保存为新列,如下所示。

temp=pd.DataFrame(df['col1'].value_counts(bins=2).reset_index()).rename(columns={'index':'bin'})

有没有办法让同一个括号'('或']'。或者我应该用另一行代码清理(替换)?

请帮助理解问题。 提前谢谢。

2 个答案:

答案 0 :(得分:2)

它使用(]表示打开和关闭间隔。您的bin实际上是一个间隔,例如(2.0, 3.0]表示独占2和包含3。

(2.0, 3.0]: 2.0 < x <= 3.0

如果您需要更改垃圾箱的格式,请在reset_index之后使用以下命令:

df['Bins'] = df.iloc[:, 0].apply(lambda x: '[{}: {}]'.format(x.left, x.right))

<强>输出

df['Bins']
Out[121]:
0    [-0.002: 0.0]
1     [0.0: 0.001]
Name: Bins, dtype: object

答案 1 :(得分:2)

如果需要将Intervalindex转换为tuple s:

,则可以使用
df1 = df['col1'].value_counts(bins=2).reset_index().rename(columns={'index':'bin'})
df1['bins'] = [(x.left, x.right) for x in df1['bin']]
print (df1)
            bin  col1          bins
0  (0.997, 2.0]    11  (0.997, 2.0)
1    (2.0, 3.0]     6    (2.0, 3.0)

list s:

df1['bins'] = [[x.left, x.right] for x in df1['bin']]
print (df1)
            bin  col1          bins
0  (0.997, 2.0]    11  [0.997, 2.0]
1    (2.0, 3.0]     6    [2.0, 3.0]

如果想要string s:

df1['bins'] = ['({}, {})'.format(x.left, x.right) for x in df1['bin']]
print (df1)
            bin  col1          bins
0  (0.997, 2.0]    11  (0.997, 2.0)
1    (2.0, 3.0]     6    (2.0, 3.0)

对于新列:

df1[['l', 'r']] = pd.DataFrame([(x.left, x.right) for x in df1['bin']])
print (df1)
            bin  col1      l    r
0  (0.997, 2.0]    11  0.997  2.0
1    (2.0, 3.0]     6  2.000  3.0