【发布时间】:2015-10-19 20:46:35
【问题描述】:
背景
有 5 个 DataFrame,我称它们为 b1, b2, b3, b4, b5。
它们的数据结构由['Date', 'Value'] 列组成
我得到了 2014 年到 2015 年的数据。
问题
每个 DataFrame 都有不同的日期计数系统。所以,我想去掉 DataFrames 中日期不匹配的行。
我该怎么做?
我尝试过的
所以,如果Date的数据没有包含在所有DataFrame中,我将删除所有数据:b1, b2, b3, b4, b5
这是第一次工作
for i in range(len(b2.index)):
k = 0
for j in range(len(b1.index)):
if b2['Date'][i] == b1['Date'][j]:
k = k+1
else:
k = k
if k == 1:
pass
if k == 0:
b2 = b2.drop([i])
但是,在那之后我又执行了一次这段代码,会出现这样的错误:
KeyError Traceback(最近一次调用最后一次) 在 () 2k = 0 3for j in range(len(b2.index)): ----> 4 如果 b1['Date'][i] == b2['Date'][j]: 5 k = k+1 6 其他:
C:\Users\cms\Anaconda\lib\site-packages\pandas\core\series.pyc in getitem(self, key) 519def getitem(自我,钥匙): 520尝试: --> 521 结果 = self.index.get_value(self, key) 522 523 如果不是 np.isscalar(结果):
C:\Users\cms\Anaconda\lib\site-packages\pandas\core\index.pyc in get_value(self, series, key) 1593 1594 尝试: -> 1595 返回 self._engine.get_value(s, k) 1596 除了 KeyError 作为 e1: 1597 如果 len(self) > 0 和 self.inferred_type in ['integer','boolean']:
pandas\index.pyx in pandas.index.IndexEngine.get_value (pandas\index.c:3113)()
pandas\index.pyx in pandas.index.IndexEngine.get_value (pandas\index.c:2844)()
pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:3704)()
pandas\hashtable.pyx in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:7224)()
pandas\hashtable.pyx in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:7162)()
密钥错误:28L
我想做的是
mlist = (b1,b2,b3,b4,b5)
for q in mlist:
for r in mlist:
for i in range(len(q.index)):
k = 0
for j in range(len(r.index)):
if q['Date'][i] == r['Date'][j]:
k = k+1
else:
k = k
if k == 1:
pass
if k == 0:
q = q.drop([i])`enter code here`
【问题讨论】:
-
q.drop将索引值作为 arg,不一定是整数索引。试试 q.drop(q.index[i])。另外,不需要k,只需做if q['Date'][i] == r['Date'][j]: continue和else: q = q.drop(q.index[i])
标签: python-2.7 pandas