【问题标题】:Pandas Iterate through rows, compare column value with string in a list, return a value from another columnPandas遍历行,将列值与列表中的字符串进行比较,从另一列返回值
【发布时间】:2019-03-09 18:31:52
【问题描述】:

目前我正在尝试遍历数据框,将字符串列表中的每个值与数据框中某一列中的值进行比较。如果这是比较,则将来自同一行的不同列的值附加到单独的列表中。

list_of_words = 'yes', 'no', 'maybe'
appendList = []
    for word in list_of_words: 
        for row in dataframe1.iterrows():
            if row['A'] == word:
                appendList.append(row['B'])
                return appendList

问题是我不确定如何将列表中的值与列值进行比较。一般来说,我对 pandas 和 python 还是很陌生,但到目前为止,方便的方法都很棒。只是不确定如何工作以返回我需要的东西。对任何有帮助的文档的任何帮助或建议将不胜感激!

【问题讨论】:

  • dataframe1[dataframe1[‘A’].isin(list_of_words)][‘B’].tolist() ?
  • 谢谢克里斯 A!那工作得很好。现在我有了一个可以使用的列表。

标签: python pandas loops for-loop


【解决方案1】:

尝试以下方法:

list_of_words = ['yes', 'no', 'maybe']

appendList = dataframe1.B[dataframe1.A.isin(list_of_words)]

【讨论】:

    【解决方案2】:

    在您的示例中,每个 row 是一个 2 元素元组,使用整数进行索引:row[0] 是行号,row[1]pandas.Series。所以使用表达式row['A']是一个TypeError。

    >>> row['A']
    TypeError: tuple indices must be integers or slices, not str
    

    您可以使用pandas.Series.tolist()pandas.Series 转换为包含该行元素的普通python 列表,然后进行比较:

    for row in dataframe1.iterrows():
        row_data = row[1].tolist() 
        if row_data[0] == word:
            appendList.append(row_data[1])
    

    作为一个列表,row_data 必须使用整数进行索引。这会降低您的代码的可读性。

    【讨论】:

    • 我现在正在运行它,我会及时通知您。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    相关资源
    最近更新 更多