[英]Python: How to find whether a specific number of items in a list are identical?
[英]How to find identical index between columns that has different number of items in python?
例如,我有兩個日期時間列:
col1 = [2019-01-01 03:00:00,
2019-01-01 03:01:00,
2019-01-01 03:02:00]
col2 = [2019-01-01 02:59:00,
2019-01-01 03:00:00,
2019-01-01 03:01:00,
2019-01-01 03:02:00,
2019-01-01 03:03:00]
每個都具有[0,1,2]和[0,1,2,3,4]的索引。
所以,我想得到的是[1,2,3],它是col2的索引( 與col1重疊的元素 )。
以下是我的代碼,它不起作用:
ind = []
for x in range(len(col1)):
rw = np.where(col2 == col1[x])
ind.append(int(rw[0]))
有沒有簡單的方法來解決這個問題?
Oneliner使用enumerate
:
[i for i, t in enumerate(col2) if t in col1]
# [1,2,3]
你也可以使用pandas.Series.isin
:
import pandas as pd
col1 = pd.Series(["2019-01-01 03:00:00",
"2019-01-01 03:01:00",
"2019-01-01 03:02:00"])
col2 = pd.Series(["2019-01-01 02:59:00",
"2019-01-01 03:00:00",
"2019-01-01 03:01:00",
"2019-01-01 03:02:00",
"2019-01-01 03:03:00"])
col2.index[col2.isin(col1)].tolist()
# [1,2,3]
如果您不需要使用numpy來解決此問題,那么您可以遍歷一個列表並檢查另一個列表中是否存在每個元素。
>>> col1 = ["2019-01-01 03:00:00",
"2019-01-01 03:01:00",
"2019-01-01 03:02:00"]
>>> col2 = ["2019-01-01 02:59:00",
"2019-01-01 03:00:00",
"2019-01-01 03:01:00",
"2019-01-01 03:02:00",
"2019-01-01 03:03:00"]
>>> ind = []
>>> for element in col1:
if element in col2:
ind.append(element)
>>> print(ind)
['2019-01-01 03:00:00', '2019-01-01 03:01:00', '2019-01-01 03:02:00']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.