Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取并生成两个字符串中不相等字符数的直方图_Python_Pandas_Dictionary_Histogram_Counter - Fatal编程技术网

Python 获取并生成两个字符串中不相等字符数的直方图

Python 获取并生成两个字符串中不相等字符数的直方图,python,pandas,dictionary,histogram,counter,Python,Pandas,Dictionary,Histogram,Counter,例如,la有以下示例(仅供解释): 第一列表示实际值,第二列表示预测值。我想比较每一行的列的值,以检测两个字符串的不同之处 我做了以下工作: ifor i in range(len(df)): if df.manual_raw_value[i] != df.raw_value[i]: text=df.manual_raw_value[i] text2=df.raw_value[i] x=len(df.manual_raw_value[i]) y = len(df.

例如,la有以下示例(仅供解释):

第一列表示实际值,第二列表示预测值。我想比较每一行的列的值,以检测两个字符串的不同之处

我做了以下工作:

ifor i in range(len(df)):
if df.manual_raw_value[i] != df.raw_value[i]:
    text=df.manual_raw_value[i]
    text2=df.raw_value[i]
    x=len(df.manual_raw_value[i])
    y = len(df.raw_value[i])
    z=min(x,y)
    for t in range(z):
        if text[t] != text2[t]:
            d= (text[t],text2[t])
            dictionnary.append(d) 
            print(dictionnary)


 [  ('a', 'n'),
 ('n', 'g'),
 ('g', 'e'),
 ('e', '.'),
 ('.', 'f'),
 ('f', 'r'),
 ("'", 'E'),
 ('E', 'S'),
 ('S', 'C'),
 ('C', 'O'),
 ('O', 'M'),
 ('M', 'P'),
 ('P', 'T'),
 ('T', 'E'),
 ('C', 'Q'),
 ('6', 'G'),
 ('9', 'o'),
 ('1', 'i'),
 ("'", 'E'),
 ('E', 'a'),
 ('a', 'u'),
 ('.', ','),
 ...]
字典的键代表了真正的值。 现在我想计算一下发生的次数如下:

[('a' : 'e'), ('a','e'), ('b','d')]
变成

[('a' : 'e') : 2,  ('b','d') : 1] 
我试过:

  collections.Counter(dictionnary)
   [ ('/', '1'): 2,
         ('/', 'M'): 2,
         ('/', 'W'): 2,
         ('/', 'h'): 8,
         ('/', 'm'): 2,
         ('/', 't'): 6,
         ('0', '-'): 2,
         ('0', '1'): 2,
         ('0', '3'): 2,
         ('0', '4'): 6,
         ('0', '5'): 2,
         ('0', '6'): 2,
         ('0', '7'): 4,
         ('0', '9'): 2,
         ('0', 'C'): 2,
         ('0', 'D'): 4,
         ('0', 'O'): 16,
         ('0', 'Q'): 4,
         ('0', 'U'): 2,
         ('0', 'm'): 4,
         ('0', 'o'): 2,
         ('0', '\xc3'): 2,
         ('1', ' '): 2,
         ('1', '/'): 2,
         ('1', '0'): 4,
         ('1', '2'): 2,
         ('1', '3'): 2,
         ('1', '4'): 2,
         ('1', '6'): 2,
         ('1', 'H'): 2,
         ('1', 'I'): 24,
         ('1', 'S'): 2,
         ('1', 'i'): 6,
         ('1', 'l'): 6,
         ('2', '3'): 2,
         ('2', '8'): 2,
         ('2', 'N'): 2,
         ('2', 'S'): 2, ..]
要绘制直方图,我尝试了以下操作:

import numpy as np
import matplotlib.pyplot as plt

pos = np.arange(len(dictionnary.keys()))
width = 1.0    

ax = plt.axes()
ax.set_xticks(pos + (width / 2))
ax.set_xticklabels(dictionnary.keys())

plt.bar(dictionary.keys(), ******, width, color='g')
plt.show()
然而:
dictionnary.keys()
返回以下错误:

Traceback (most recent call last):
  File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-94-5d466717162c>", line 1, in <module>
    dictionnary_new.keys()
AttributeError: 'list' object has no attribute 'keys'
回溯(最近一次呼叫最后一次):
文件“/home/ahmed/anaconda3/envs/cv/lib/python2.7/site packages/IPython/core/interactiveshell.py”,第2881行,运行代码
exec(代码对象、self.user\u全局、self.user\n)
文件“”,第1行,在
词汇表_new.keys()
AttributeError:“列表”对象没有属性“键”
编辑1:

 dictionnary_new = collections.Counter(dictionnary) # it works
    import numpy as np
    import matplotlib.pyplot as plt

    pos = np.arange(len(dictionnary_new.keys()))
    width = 1.0    

    ax = plt.axes()
    ax.set_xticks(pos + (width / 2))
    ax.set_xticklabels(dictionnary_new.keys())

    plt.bar(dictionnary_new.keys(), dictionnary_new.values(), width, color='g')
    plt.show()


l got the following error :


        Traceback (most recent call last):
          File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-

packages/IPython/core/interactiveshell.py", line 2881, in run_code
        exec(code_obj, self.user_global_ns, self.user_ns)
      File "<ipython-input-117-4155944ddaf3>", line 11, in <module>
        plt.bar(dictionnary_new.keys(), dictionnary_new.values(), width, color='g')
      File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/matplotlib/pyplot.py", line 2705, in bar
        **kwargs)
      File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/matplotlib/__init__.py", line 1892, in inner
        return func(ax, *args, **kwargs)
      File "/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-packages/matplotlib/axes/_axes.py", line 2105, in bar
        left = [left[i] - width[i] / 2. for i in xrange(len(left))]
    TypeError: unsupported operand type(s) for -: 'tuple' and 'float'
dictionnary\u new=collections.Counter(dictionnary)#有效
将numpy作为np导入
将matplotlib.pyplot作为plt导入
pos=np.arange(len(dictionnary\u new.keys()))
宽度=1.0
ax=plt.axs()
轴设置(位置+(宽度/2))
ax.set\u xticklabels(字典\u new.keys())
plt.bar(dictionnary\u new.keys(),dictionnary\u new.values(),宽度,color='g')
plt.show()
我得到了以下错误:
回溯(最近一次呼叫最后一次):
文件“/home/ahmed/anaconda3/envs/cv/lib/python2.7/site-
packages/IPython/core/interactiveshell.py”,第2881行,运行代码
exec(代码对象、self.user\u全局、self.user\n)
文件“”,第11行,在
plt.bar(dictionnary\u new.keys(),dictionnary\u new.values(),宽度,color='g')
文件“/home/ahmed/anaconda3/envs/cv/lib/python2.7/site packages/matplotlib/pyplot.py”,第2705行,条形图
**kwargs)
文件“/home/ahmed/anaconda3/envs/cv/lib/python2.7/site packages/matplotlib/_init__.py”,第1892行,内部
返回函数(ax,*args,**kwargs)
文件“/home/ahmed/anaconda3/envs/cv/lib/python2.7/site packages/matplotlib/axes/_axes.py”,第2105行,条形图
左=[左[i]-宽度[i]/2。对于X范围内的i(len(左))]
TypeError:-:“tuple”和“float”的操作数类型不受支持

非常感谢

首先,我认为您的配对示例中有一个输入错误:

>>> lst = [{'a': 'e'}, {'a': 'e'}, {'b': 'd'}]
>>> collections.Counter([tuple(i.items()) for i in lst])
Counter({(('a', 'e'),): 2, (('b', 'd'),): 1})
话虽如此,我认为这不是解决这个问题的正确方法。在代码中,当您向
字典
变量添加内容时,不要使用字典,而是使用元组!替换:

d= {text[t] : text2[t]}
dictionnary.append(d)
与:

然后你可以使用:

collections.Counter(dictionnary)

你喜欢这个工作吗

df['string diff'] = df.apply(lambda x: distance.levenshtein(x['Real Value'], x['Predicted Values']), axis=1)
plt.hist(df['string diff'])
plt.show()

非常感谢。我在你建议的时候更新了我的密码。但是,dictionnay.key()不起作用。它返回dictionnary_new.keys()AttributeError:'list'对象没有属性'keys',请查看我的更新我猜您现在的问题是在打印之前。您需要首先获取
dictionnary\u new=collections.Counter(dictionnary)
,然后将其用于打印:
plt.bar(dictionnary\u new.keys()…
检查pyplot的文档。如果要将键用作标签,则需要设置刻度。请尝试
plt.bar(range(len(dictionnary\u new)),dictionnary\u new.values(),width,color='g')
如何导入距离。levenshteinpip3安装距离
collections.Counter(dictionnary)
df['string diff'] = df.apply(lambda x: distance.levenshtein(x['Real Value'], x['Predicted Values']), axis=1)
plt.hist(df['string diff'])
plt.show()