【问题标题】:pandas value_counts with bins argument带有 bins 参数的熊猫 value_counts
【发布时间】:2018-04-19 18:28:56
【问题描述】:

我有一个这样的数据框,

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'})

有什么方法可以保留相同的括号'('或']'。还是我应该用另一行代码清理(替换)它?

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

【问题讨论】:

  • 预期输出是多少?
  • 在索引列中应该只包含 () 或 []。我不想混合括号。例如:(0.997, 2.0] 可以是 (0.997, 2.0) 或 [0.997, 2.0]
  • Intervalindex,需要转成list吗?

标签: python pandas


【解决方案1】:

如果需要,您可以使用将Intervalindex 转换为tuples:

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)

lists:

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]

如果还想strings:

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

【讨论】:

    【解决方案2】:

    它使用(] 表示间隔的打开和关闭。你的bin其实是一个区间,比如(2.0, 3.0]表示独占2和独占3。

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

    如果您需要更改 bin 的格式,请在 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
    

    【讨论】:

      猜你喜欢
      • 2018-11-20
      • 2019-01-18
      • 2018-09-06
      • 1970-01-01
      • 2016-03-21
      • 2014-05-06
      • 2019-10-21
      • 2022-10-13
      • 2022-11-16
      相关资源
      最近更新 更多