Python 带bins参数的pandas值_计数

Python 带bins参数的pandas值_计数,python,pandas,Python,Pandas,我有一个这样的数据框 col1 1 2 3 2 2 3 1 1 2 3 1 1 3 3 1 1 3 当我计算时 打印df['col1']。值\u计数(箱子=2) 它给了我 (0.997, 2.0] 11 (2.0, 3.0] 6 Name: col1, dtype: int64 结果是好的。但在索引中,它给出了混合的(&])。 为什么它的行为是这样的。因为我想将索引保留为一个新列,如下所示 temp=pd.DataFrame(df['col1'].value_计数(bin=

我有一个这样的数据框

col1
1
2
3
2
2
3
1
1
2
3
1
1
3
3
1
1
3
当我计算时

打印df['col1']。值\u计数(箱子=2)

它给了我

(0.997, 2.0]    11
(2.0, 3.0]       6
Name: col1, dtype: int64
结果是好的。但在索引中,它给出了混合的
&
]
)。 为什么它的行为是这样的。因为我想将索引保留为一个新列,如下所示

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

有没有办法保留相同的括号“(”或“]”。或者我应该用另一行代码来清除(替换)它

请帮助理解这个问题。 提前感谢。

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

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

df['Bins']
Out[121]:
0    [-0.002: 0.0]
1     [0.0: 0.001]
Name: Bins, dtype: object
它使用
]
来表示间隔的打开和关闭。您的bin实际上是一个间隔,例如
(2.0,3.0]
表示独占2和包含3

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

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

如果需要,可以使用转换为
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)
或至
列表
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

如果需要,可以使用转换为
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)
或至
列表
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

什么是预期输出?在索引列中,它应该只包含()或[]。我不希望括号混合。例如:(0.997,2.0)它可以是(0.997,2.0)或调用的[0.997,2.0],所以需要将其转换为列表?在索引列中,它应该只包含()或[]。我不希望括号混合。例如:(0.997,2.0)它可以是(0.997,2.0)或[0.997,2.0],因此需要将其转换为列表吗?