KeyError : 0 熊猫
Posted
技术标签:
【中文标题】KeyError : 0 熊猫【英文标题】:KeyError : 0 Pandas 【发布时间】:2018-03-16 21:25:51 【问题描述】:我需要帮助。我正在尝试过滤并写入另一个 csv 文件,该文件包含在 elapsed_seconds 列中 10769 秒后收集的数据以及加速度幅度。但是,我得到 KeyError: 0...
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv(accelDataPath)
data.columns = ['t', 'x', 'y', 'z']
# calculate the magnitude of acceleration
data['m'] = np.sqrt(data['x']**2 + data['y']**2 + data['z']**2)
data['datetime'] = pd.DatetimeIndex(pd.to_datetime(data['t'], unit = 'ms').dt.tz_localize('UTC').dt.tz_convert('US/Eastern'))
data['elapsed_seconds'] = (data['datetime'] - data['datetime'].iloc[0]).dt.total_seconds()
i=0
csv = open("filteredData.csv", "w+")
csv.write("Event at, Magnitude \n")
while (i < len(data[data.elapsed_seconds > 10769])):
csv.write(str(data[data.elapsed_seconds > 10769][i]) + ", " + str(data[data.m][i]) + "\n")
csv.close()
我得到的错误是:
Traceback (most recent call last):
File "C:\Users\Desktop\AnalyzingData.py", line 37, in <module>
csv.write(str(data[data.elapsed_seconds > 10769][i]) + ", " + str(data[data.m][i]) + "\n")
File "C:\python\lib\site-packages\pandas\core\frame.py", line 1964, in __getitem__
return self._getitem_column(key)
File "C:\python\lib\site-packages\pandas\core\frame.py", line 1971, in _getitem_column
return self._get_item_cache(key)
File "C:\python\lib\site-packages\pandas\core\generic.py", line 1645, in _get_item_cache
values = self._data.get(item)
File "C:\python\lib\site-packages\pandas\core\internals.py", line 3590, in get
loc = self.items.get_loc(item)
File "C:\python\lib\site-packages\pandas\core\indexes\base.py", line 2444, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5280)
File "pandas\_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5126)
File "pandas\_libs\hashtable_class_helper.pxi", line 1210, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20523)
File "pandas\_libs\hashtable_class_helper.pxi", line 1218, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20477)
KeyError: 0
【问题讨论】:
很明显,您的数据框没有名为0
的列。然而data[data.elapsed_seconds > 10769][i]
在i == 0
时选择列0
。另外,看起来你正在编写一个无限循环......
感谢您的澄清。我可以知道如何初始化以使第一行 data[data.elapsed_seconds > 10769] 是第一行吗?
知道了。试试data[data.elapsed_seconds > 10769].iloc[i]
,这会选择第一行。
Pandas - Get first row value of a given column的可能重复
【参考方案1】:
改变这一行
csv.write(
str(data[data.elapsed_seconds > 10769][i]) + ", " + str(data[data.m][i]) + "\n"
)
到这里:
csv.write(
str(data[data.elapsed_seconds > 10769].iloc[i]) + ", " + str(data[data.m].iloc[i]) +"\n"
)
另外,请注意,在 while 循环中,您并没有像 i += 1
这样增加 i
。
或者,最好使用df.to_csv
,如下所示:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv(accelDataPath)
data.columns = ['t', 'x', 'y', 'z']
# calculate the magnitude of acceleration
data['m'] = np.sqrt(data['x']**2 + data['y']**2 + data['z']**2)
data['datetime'] = pd.DatetimeIndex(pd.to_datetime(data['t'], unit = 'ms').dt.tz_localize('UTC').dt.tz_convert('US/Eastern'))
data['elapsed_seconds'] = (data['datetime'] - data['datetime'].iloc[0]).dt.total_seconds()
# write to csv using data.to_csv
data[data.elapsed_seconds > 10769][['elapsed_seconds', 'm']].to_csv("filteredData.csv",
sep=",",
index=False)
【讨论】:
它不起作用...它产生另一组错误... raise KeyError('%s not in index' % objarr[mask]) KeyError: '[ 0.20489437 0.21313549 0.22022774 .. ., 1.53666405 1.31770629\n 1.55170659] 不在索引中' 索引([u't', u'x', u'y', u'z', u'm', u'datetime', u'elapsed_seconds'], dtype='对象')【参考方案2】:我遇到了同样的问题,通过recommendation 解决了这个问题。简而言之,不要使用df[0]
,而是使用显式的df['columnname']
【讨论】:
以上是关于KeyError : 0 熊猫的主要内容,如果未能解决你的问题,请参考以下文章