无法将字符串转换为浮点数 - Pandas 阅读专栏

Could not convert string to float - Pandas Read Column

我正在尝试使用 Pandas 绘制给定输入的散点图。我收到以下错误。

输入:

tweetcricscore  34 #afgvssco   51
tweetcricscore  23 #afgvszim   46
tweetcricscore  24 #banvsire   12
tweetcricscore  456 #banvsned  46
tweetcricscore  653 #canvsnk   1
tweetcricscore  789 #cricket   178
tweetcricscore  625 #engvswi   46
tweetcricscore  86 #hkvssco    23
tweetcricscore  3 #indvsban    1
tweetcricscore  87 #sausvsvic  8
tweetcricscore  98 #wt20       56

代码:

import numpy as np
import matplotlib.pyplot as plt
from pylab import*
import math
from matplotlib.ticker import LogLocator
import pandas as pd

df = pd.read_csv('input.csv', header = None)

df.columns = ['col1','col2','col3','col4']

plt.scatter(x='col2', y='col4', s=120, c='b', label='Highly Active')

plt.legend(loc='upper right')
plt.xlabel('Freq (x)')
plt.ylabel('Freq(y)')
#plt.gca().set_xscale("log")
#plt.gca().set_yscale("log")
plt.show()

我试图从 4 列中绘制成对的 col[1] 和 col[3] 数据点在散点图中。

错误

Traceback (most recent call last):
  File "00_scatter_plot.py", line 14, in <module>
    plt.scatter(x='col2', y='col3', s=120, c='b', label='Highly Active')
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 3087, in scatter
    linewidths=linewidths, verts=verts, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 6337, in scatter
    self.add_collection(collection)
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 1481, in add_collection
    self.update_datalim(collection.get_datalim(self.transData))
  File "/usr/lib/pymodules/python2.7/matplotlib/collections.py", line 185, in get_datalim
    offsets = np.asanyarray(offsets, np.float_)
  File "/usr/local/lib/python2.7/dist-packages/numpy/core/numeric.py", line 514, in asanyarray
    return array(a, dtype, copy=False, order=order, subok=True)
ValueError: could not convert string to float: col2

这是您的错误信息:

File "00_scatter_plot.py", line 14, in <module>
    plt.scatter(x='col2', y='col3', s=120, c='b', label='Highly Active')
ValueError: could not convert string to float: col2

如您所见,您正在尝试将字符串 "col2" 转换为浮点数。

通过查看您的代码,您似乎想要这样的东西:

plt.scatter(x=df['col2'], y=df['col4'], s=120, c='b', label='Highly Active')

而不是:

plt.scatter(x='col2', y='col4', s=120, c='b', label='Highly Active')

尝试改变:

plt.scatter(x='col2', y='col4', s=120, c='b', label='Highly Active')

至:

df.plot.scatter(x='col2', y='col4', s=120, c='b', label='Highly Active')

对我有用: