【问题标题】:How to get the index value of column value compared with another column value如何获取列值与另一列值比较的索引值
【发布时间】:2023-03-19 04:00:01
【问题描述】:

我想要这样的东西。

Index    Sentence
0           I
1           want
2           like 
3           this

Keyword     Index
 want        1
 this        3

我尝试使用df.index("Keyword"),但它并没有为所有行提供。如果有人解决这个问题,那将非常有帮助。

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    仅将isinboolean indexing 一起使用:

    df = df[df['Sentence'].isin(['want', 'this'])]
    print (df)
       Index Sentence
    1      1     want
    3      3     this
    

    编辑:如果需要通过另一列进行比较:

    df = df[df['Sentence'].isin(df['Keyword'])]
    #another DataFrame df2
    #df = df[df['Sentence'].isin(df2['Keyword'])]
    

    如果需要索引值:

    idx = df.index[df['Sentence'].isin(df['Keyword'])]
    #alternative
    #idx = df[df['Sentence'].isin(df['Keyword'])].index
    

    【讨论】:

    • 我应该根据列名“关键字”而不是“关键字”列中的值来获取索引值
    • 太棒了。但是我没有得到第一个单词的索引。例如,Index Sentence 3 this 这样我得到了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多