1

Take this csv as an example:

Col1, Col2
1,3,
0,5,
1,4
0,7

Say that I have a list, and I want to append the values of Col2 to the list only if the value of Col1 in the same row is 1. The resulting list should be [3,4].

How can I do this with pandas without using iterrows()?

3 Answers 3

1
  1. I think .loc is the most pythonic and simplest method.

    df.loc[df['Col1'] == '1']['Col2'].to_list()
    
  2. An alternative using np.where:

    import numpy as np
    df['Col3'] = np.where(df['Col1'] == 1, df['Col2'], '')
    listt = list(filter(None,df['Col3'].to_list()))
    
  3. zip is a loop alternative to iterrows.

    listt = []
    for x, y in zip(df['Col1'], df['Col2']):
        if x == 1:
            listt.append(y)
    
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming you've read in your csv into a dataframe named df, you could use this:

wanted = df.query('Col1 == 1')['Col2'].values
mylist.extend(wanted)

Comments

0
import pandas as pd

lst_result=[]
for ind, row in df.iterrows():
    if df.at[ind,'Col1'] == 1:
        lst_result.append(df.at(ind,['Col2']))
print(lst_result)

2 Comments

Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.