1

I have a problem with 'loc' and'iloc' .So I have a list and a data frame, I want to check if the data in list and date in data frame of a column is matching. if matching I need to copy it to a new data frame. I am half way but I don't know how to copy the rows from a data frame to new one based on the index. How do we do that?

Code:

d = {'col1': [1, 2,3,5,6], 'col2': [3, 4,5,6,7]}
cols = list(df.columns)
df1=pd.DataFrame(columns=cols) 
lst=['1','2']
df1 = pd.DataFrame()
for index,v in df['col1'].iteritems():
    for l in lst:
        if l == v:
            df1 = df.loc[index] 

which gives nothing(empty data frame):

col1    col2

Actual output:

df1 =
   col1 col2
0   1   3
1   2   4
5
  • 1
    You have data type problems. lst is a string, your default index in df is an integer. l will not equal v. change to lst=[1,2] Commented Mar 18, 2021 at 18:46
  • 1
    loc is using label based index, iloc is using integer position based indexing. Confusion happens mostly because with the default range index of a dataframe, the indexing are integer matching exactly the position based of the index, thus either will work. Commented Mar 18, 2021 at 18:49
  • 2
    aside from the data type problem, try isin and boolean indexing df.loc[df['col1'].isin(lst)]. Commented Mar 18, 2021 at 18:52
  • @ScottBoston Thanks for the explanation .Yes, it did Commented Mar 18, 2021 at 19:07
  • @QuangHoang Your approach was simple.Thanks alot :) helped me alot Commented Mar 18, 2021 at 19:08

0

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.