开发者社区> 问答> 正文

如何在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]))

有没有简单的方法来解决这个问题?

展开
收起
一码平川MACHEL 2019-02-28 14:22:14 1907 0
1 条回答
写回答
取消 提交回答
  • 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]

    2019-07-17 23:29:45
    赞同 展开评论 打赏
问答分类:
问答地址:
相关产品:
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载