【发布时间】:2017-01-06 09:36:04
【问题描述】:
我正在尝试获取两个熊猫数据表的相同元素,并对数据进行索引并将其合并。我将它用于大量数据(数百万)。第一个表(df)是常量,第二个(d2)在每个循环中都在变化,新元素将与第一个表合并。
这是我的这个过程的代码:
df = pd.read_csv("inputfile.csv",header=None)
d1 = pd.DataFrame(df).set_index(0)
for i in range(0, len(df)):
try:
follower_id=twitter.get_followers_ids(user_id=df.iloc[i][0],cursor=next_cursor)
f=follower_id['ids']
json.dumps(f)
d2 = pd.DataFrame(f).set_index(0)
match_result = pd.merge(d1,d2,left_index=True,right_index=True)
fk=[df.iloc[i][0] for number in range(len(match_result))]
DF = pd.DataFrame(fk)
DF.to_csv(r'output1.csv',header=None,sep=' ',index=None)
match_result.to_csv(r'output2.csv', header=None, sep=' ')
我经历过,这段代码运行良好一段时间,但之后 - 可能它与第二个数据库大小相关,每个循环都会改变 - 程序给我以下错误消息,并停止运行:
Traceback (most recent call last):
File "halozat3.py", line 39, in <module>
d2 = pd.DataFrame(f).set_index(0) #1Trump koveto kovetolistaja
File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 2372, in set_index
level = frame[col].values
File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 1678, in __getitem__
return self._getitem_column(key)
File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 1685, in _getitem_column
return self._get_item_cache(key)
File "/usr/lib/python2.7/dist-packages/pandas/core/generic.py", line 1052, in _get_item_cache
values = self._data.get(item)
File "/usr/lib/python2.7/dist-packages/pandas/core/internals.py", line 2565, in get
loc = self.items.get_loc(item)
File "/usr/lib/python2.7/dist-packages/pandas/core/index.py", line 1181, in get_loc
return self._engine.get_loc(_values_from_object(key))
File "index.pyx", line 129, in pandas.index.IndexEngine.get_loc (pandas/index.c:3656)
File "index.pyx", line 149, in pandas.index.IndexEngine.get_loc (pandas/index.c:3534)
File "hashtable.pyx", line 381, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:7035)
File "hashtable.pyx", line 387, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6976)
KeyError: 0
可能是什么问题?
【问题讨论】:
-
很简单,
0不是列标签。你试过d2 = pd.DataFrame(f).set_index('ids')吗? -
我建议在发生 KeyError 时捕获异常并打印 f。通过这种方式,您可以看到这个 f 与您的预期有何不同,因为出于某种原因,这个 f 似乎没有第 0 列,而其他的则有。
-
我试过了,但是给了我:
KeyError: 'ids' -
你能提供“f”的输出吗?
-
我写了一个异常,但也退出了,同样的错误信息。这是我的例外:
try:pandas codesexcept (ValueError,TypeError,IndexError) as er:print er.error_codeprint f@Skirrebattie 有什么问题?
标签: python pandas twitter bigdata