Python Pandas错误类型错误:不支持/:“str”和“int”的操作数类型

2024-04-29 18:43:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力学习如何在Python中使用熊猫。我对我的熊猫数据框做数学计算有问题。 现在我的数据帧看起来像这样:

打印(标记)

                0      1      2       3       4           5             6
0       447366345  -2.04  -2.69  176.98  418.84  34.3167521  -118.4068498
1       447406197  -2.34  -2.18  176.88  418.77  34.3167522  -118.4068499
2       447446155  -2.63  -1.56  176.74  418.77  34.3167522  -118.4068499
3       447486653  -2.89  -0.95  176.58  418.84  34.3167522  -118.4068499
4       447526241  -3.12  -0.42  176.43  418.84  34.3167522  -118.4068499
5       447566373  -3.34  -0.07  176.32  418.84  34.3167522  -118.4068497
6       447606036  -3.56   0.05  176.26  418.66  34.3167523  -118.4068497
7       447645783  -3.77  -0.03  176.28  418.66  34.3167523  -118.4068497
8       447686269  -3.95  -0.31  176.43  418.95  34.3167523  -118.4068497

def data_reader(filename, rowname):
    with open(filename, newline='') as fp:
        yield from (row[1:] for row in csv.reader(fp, skipinitialspace=True)
            if row[0] == rowname)

mike = pd.DataFrame.from_records(data_reader('data.csv', 'mike'))

现在假设我要取0行除以1000

mark_time = mark[0] / 1000

这会产生错误

 TypeError: unsupported operand type(s) for /: 'str' and 'int'

我猜是因为当前我的数据帧不被视为INT,所以我继续做了以下工作:

mark_time = float (mark[0] / 1000)

不过,这也给了我同样的错误。有人能解释一下原因吗?

我的第二个问题是当它涉及到阴谋。我已经很好地学习了matplotlib,我想在我的Panda数据帧上使用它。目前我的做法是:

fig1 = plt.figure(figsize= (10,10))
ax = fig1.add_subplot(311)
ax.plot(mike_time, mike[0], label='mike speed', color = 'red')
plt.legend(loc='best',prop={'size':10})

我可以用我的数据帧替换mike_time和mike[0]吗?


Tags: csv数据fromfordatatime错误filename
2条回答

您需要使用pandas.read_csv而不是python的csv。

在这里,可以使用dtype参数为其提供正确的数据类型,以便其使用:

来自熊猫documentation

dtype : Type name or dict of column -> type, default None Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32} (unsupported with engine='python'). Use str or object to preserve and not interpret dtype.

如果必须在pandas外部解析CSV,则可以使用“from_records”导入,强制使用float=True。Reference

coerce_float : boolean, default False Attempt to convert values to non-string, non-numeric objects (like decimal.Decimal) to floating point, useful for SQL result sets

您需要使用pandas read_csv,它将自动为每个列分配最合适的类型。如果有任何混合类型的列,它将警告您。然后可以再次运行它,显式设置类型。

相关问题 更多 >