如何循环浏览和匹配两个日期列,并将关联的代码提取到一个新列表中



我有一个pandas-df,其中包含一个代码列和一个日期列(类型:object(,其中包含289k个条目。每个日期都有多个代码,因此在下一列中fx 10行具有相同的日期和不同的代码,然后20行具有新的日期和新的代码等。我还有一个包含103个条目的日期(类型:str(的ndarray。我想将我的ndarray中的所有日期与df匹配,并且每次找到匹配时;代码";从该特定日期到新列表。我尝试了很多不同的事情,但都没有成功。

filtered_codes = []
for j in raw_data.Dates:
for q in reb_dates:
if j == q:
filtered_codes.append(raw_data.codes)
filtered_codes = []
for j in reb_dates:
for q in raw_data.Dates:
if raw_data['Dates'][q] == reb_dates[j]:
filtered_codes.append(raw_data.codes[q])

运行第一个会给我一个系列列表。所有列表都是相同的,该系列包含的条目与我的raw_data一样多。

如果我运行第二个例子,我会得到这个错误:

Traceback (most recent call last):
File "C:Usersxxxvenvlibsite-packagespandascoreindexesbase.py", line 3361, in get_loc
return self._engine.get_loc(casted_key)
File "pandas_libsindex.pyx", line 76, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libsindex_class_helper.pxi", line 105, in pandas._libs.index.Int64Engine._check_type
File "pandas_libsindex_class_helper.pxi", line 105, in pandas._libs.index.Int64Engine._check_type
KeyError: '2013-02-20'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "C:Usersxxx.py", line 73, in <module>
if raw_data['Dates'][q] == reb_dates[j]:
File "C:Usersxxxvenvlibsite-packagespandascoreseries.py", line 942, in __getitem__
return self._get_value(key)
File "C:Usersxxxvenvlibsite-packagespandascoreseries.py", line 1051, in _get_value
loc = self.index.get_loc(label)
File "C:Usersxxxvenvlibsite-packagespandascoreindexesbase.py", line 3363, in get_loc
raise KeyError(key) from err
KeyError: '2013-02-20'
Process finished with exit code 1

是循环导致了问题还是数据类型?我对蟒蛇没什么经验。任何帮助都表示感谢

规则是尽可能避免数据帧上的任何Python级别的循环。

但让我们先看看您当前的代码:

filtered_codes = []
for j in raw_data.Dates:
for q in reb_dates:
if j == q:
filtered_codes.append(raw_data.codes) # Oops !!

将完整的列raw_data.codes附加到列表中,并在每次"日期"列中出现reb_dates中的日期时执行此操作。不是你想要的。。。

filtered_codes = []
for j in reb_dates:
for q in raw_data.Dates:
if raw_data['Dates'][q] == reb_dates[j]:         # Oops
filtered_codes.append(raw_data.codes[q])     # Oops again...

第一行Oops应该是if q == j:,因为qj是实际的日期值,而不是它们在容器中的索引。由于q是表示日期的字符串值,而不是索引,所以下一行的raw_data.codes[q]也是一个错误。

您可以很容易地构建一个系列,其中日期是索引(具有str类型,因此是对象dtype(,值是该日期的代码集:

codes_per_date = raw_data[raw_data['Dates'].isin(reb_dates)].groupby(
'Dates')['code'].agg(set)

最新更新