【发布时间】:2019-05-04 09:59:58
【问题描述】:
这里我有要从 CSV 文件导入的数据。我在类中编写了一个方程,并求解方程数据将从 CSV 文件导入。 当我运行我的代码时,我得到了一个错误,比如“元组索引必须是整数或切片,而不是 str”,使用 panda python。 谁能帮我解决这个问题? 我在这里上传我的代码和 CSV 文件。
def time_convert(x):
h,m,s = map(int,x.split(':'))
return (h*60+m)
def ph_convert(time,we,h,a,w):
while time <= 30:
level = 1.1
level = float(level)
if w == 1:
ph= ((((6*we)+(1*h))/level -(4*a)))/time
else:
ph= ((6+((1*we)+(3*h))/level -(6 *a)))/time
break
while time <=60:
level = 1.25
level = float(level)
if w == 1:
ph= ((((6*we)+(1*h))/level -(4*a)))/time
else:
ph= ((6+((1*we)+(3*h))/level -(6 *a)))/time
break
print(ph)
data = pd.read_csv('data1.csv')
data['time'] = data['time'].apply(time_convert)
we = data['we'].astype(float)
h = data['h'].astype(float)
a = data['a'].astype(float)
w = data['w'].astype(float)
time = data['time'].astype(float)
print(ph_convert(time,we,h,a,w))
我的 CSV 文件的子集:
we h a w time
48.1 150 53 1 6:15:00
48.1 150 53 1 9:00:00
48.1 150 53 1 9:25:00
48.1 150 53 1 9:30:00
48.1 150 53 1 11:00:00
错误:
ValueError Traceback (most recent call last)
<ipython-input-922-9fe360350b03> in <module>()
----> 1 print(ph_convert(time,we,h,a,w))
<ipython-input-904-73455dabb050> in ph_convert(time, we, h, a, w)
3
----> 5 while time <= 30:
6 level = 1.1
7 level = float(level)
~\Anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
1571 raise ValueError("The truth value of a {0} is ambiguous. "
1572 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1573 .format(self.__class__.__name__))
1574
1575 __bool__ = __nonzero__
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
【问题讨论】:
-
time_convert 函数在做什么?
-
@MohitMotwani 它将我的时间转换为分钟。代码是:-def time_convert(x): h,m,s = map(int,x.split(':')) return (h*60+m)
-
time(和其他变量)实际上是一个系列。您的函数需要 time(int, float) 的单个值而不是系列。因此,您会收到此错误。 -
@MohitMotwani 你能给我一些解决这个错误的建议吗?我没有任何想法来解决这个问题。
-
您想要一个新列,其中每一行都有自己的 ph_convert 值吗?