繁体   English   中英

熊猫遍历行,将列值与列表中的字符串进行比较,从另一列返回值

[英]Pandas Iterate through rows, compare column value with string in a list, return a value from another column

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

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还是很陌生,但是到目前为止,便利的方法很棒。 只是不确定如何工作才能返回我需要的东西。 对任何文档的任何帮助或建议,将不胜感激!

请尝试以下操作:

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

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

在您的示例中,每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必须使用整数索引。 这会使您的代码可读性降低。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM