【发布时间】:2016-07-01 17:55:38
【问题描述】:
我想获取一个带有摄氏温度的 CSV 文件并将其转换为华氏温度。
当前尝试:
import pandas as pd
df = pd.read_csv('/temperature_data.csv', )
def f(x):
x = x * 1.8 + 32
return float(x)
df['AirTemperature'] = df.apply(f, axis=1)
如果我只是在函数中输入一个整数,我就能成功地做到这一点,但是当我尝试使用 csv 文件时,我不断收到此错误消息:
can't multiply sequence by non-int of type 'float'
我尝试将值转换为浮点数,但没有成功。
编辑: 我使用的 CSV 文件是多列的。它不仅仅是空气温度。
这里还有完整的回溯
`---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-a63269740c5c> in <module>()
----> 1 df['AirTemperature'] = df.apply(f, axis=1)
/Users/pvayn/anaconda/lib/python2.7/site-packages/pandas/core/frame.pyc in apply(self, func, axis, broadcast, raw, reduce, args, **kwds)
4040 if reduce is None:
4041 reduce = True
-> 4042 return self._apply_standard(f, axis, reduce=reduce)
4043 else:
4044 return self._apply_broadcast(f, axis)
/Users/pvayn/anaconda/lib/python2.7/site-packages/pandas/core/frame.pyc in _apply_standard(self, func, axis, ignore_failures, reduce)
4136 try:
4137 for i, v in enumerate(series_gen):
-> 4138 results[i] = func(v)
4139 keys.append(v.name)
4140 except Exception as e:
<ipython-input-3-895f5da25595> in f(x)
1 def f(x):
----> 2 x = x*1.8 + 32
3 return float(x)
/Users/pvayn/anaconda/lib/python2.7/site-packages/pandas/core/ops.pyc in wrapper(left, right, name, na_op)
647 lvalues = lvalues.values
648
--> 649 return left._constructor(wrap_results(na_op(lvalues, rvalues)),
650 index=left.index, name=left.name,
651 dtype=dtype)
/Users/pvayn/anaconda/lib/python2.7/site-packages/pandas/core/ops.pyc in na_op(x, y)
588 result = np.empty(len(x), dtype=x.dtype)
589 mask = notnull(x)
--> 590 result[mask] = op(x[mask], y)
591 else:
592 raise TypeError("{typ} cannot perform the operation "
TypeError: ("can't multiply sequence by non-int of type 'float'", u'occurred at index 0')
【问题讨论】:
-
您提供的代码对我有用,它是一个包含浮点数和整数的单列 CSV。我们能看到完整的回溯吗?
-
函数接收到的
x似乎很清楚是一个序列类型,而不是一个int。这似乎在文档中提到:pandas.pydata.org/pandas-docs/stable/generated/… 您可能需要修改f以适应它。 -
你对我如何接近@DavidZemens 有什么建议吗?
-
不是真的,以前从未使用过 Pandas,但你可以试试
df['Air Temperature'] = df['Air Temperature'].apply(f)?如果Air Temperature是一个系列,那么series对象也有一个apply方法。 -
成功了!谢谢
标签: python csv temperature