【问题标题】:Converting collection of binary data in dictionary of occurencies with python pandas使用 python pandas 转换出现字典中的二进制数据集合
【发布时间】:2016-02-13 21:56:50
【问题描述】:

我有一些 CSV 格式的数据,如下所示:

Time [s],Data
0.000916000000000,0b  1111  1110  0100  0100  0000  1111  0011  1100
0.024800000000000,0b  1111  1110  0100  0100  0000  1111  0011  1100
0.048684000000000,0b  1111  1110  0100  0100  0000  1111  0011  1100
...
4.729276000000000,0b  1111  1110  0100  1000  0000  1111  0000  1100

我想知道出现了哪些二进制代码,以及确定哪些是重要信号的频率。

我意识到这可以通过 python pandas 轻松实现:

import pandas as pd
csv_data = pd.read_csv('./captures/idle binary.csv')
occurencies = csv_data['Data'].value_counts()

这给了我这个输出:

0b  1111  1110  0100  0100  0000  1111  0011  1100    195
0b  1111  1110  0100  0000  0000  1111  0010  1100      8
0b  1111  1110  0100  1000  0000  1111  0000  1100      6
Name: Data, dtype: int64

首先,我想从数据中删除 0b 和所有空格以获取

11111110010001000000111100111100

我想转置数据,以便将出现次数作为索引

195   11111110010001000000111100111100 
  8   11111110010000000000111100101100
  6   11111110010010000000111100001100

对于我尝试使用的第一个目标

occurencies.replace('0b', '')

我试过的第二个

occurencies.transpose()

但这不起作用。我可以轻松做到

occurencies.to_dict()

然后切换 dict 键和值并编辑值,但我想用 pandas 实现相同的目标。

【问题讨论】:

  • IIUC 那么以下应该可以工作:occurencies.str.replace('0b','').str.replace(' ','') 连接 str,以实现您需要交换数据和索引的下一位,我只需构建一个交换数据的新系列周围,​​s = pd.Series(index = occurencies.values, data = occurencies.index)
  • 我已经尝试过 str.replace 但出现以下错误:raise AttributeError("Can only use .str accessor with string" AttributeError: Can only use .str accessor with string values, which use np.object_大熊猫中的数据类型

标签: python pandas str-replace series


【解决方案1】:

通常您希望您的索引表示一个唯一值,如果您使用value_counts 的结果作为索引,则很容易违反该值。

剥离字符串并重新排列列:

df = csv_data['Data'].value_counts().reset_index()
df.columns = ['byte', 'count']
df['stripped_bytes'] = df.byte.str.split().apply(lambda x: "".join(x[1:]) if len(x) else "")
df[['count', 'stripped_bytes']]
   count                    stripped_bytes
0    195  11111110010001000000111100111100
1      8  11111110010000000000111100101100
2      6  11111110010010000000111100001100

【讨论】:

  • 非常感谢您提供的解释代码。它帮助很大,我终于能够使用 str. replace() 函数去除开头的所有空格和 0b。
猜你喜欢
  • 1970-01-01
  • 2018-05-13
  • 2018-09-12
  • 1970-01-01
  • 2018-03-30
  • 2019-06-30
  • 2022-09-30
  • 2013-04-30
相关资源
最近更新 更多