0

I have a question about some code using python3/pandas.

I have a list

mylist = [2,6,7]

and a dataframe

import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split(),
                   'C': np.arange(8), 'D': np.arange(8) * 2})

Now I want to check, if an item of mylist equals a value of column C in df. If it does, make a new df2 with the rows that gave a match.

col = ["A", "B", "C", "D"]
df2 = pd.DataFrame(columns=col)
for x in mylist:
    if len(df.loc[df['C'] == x])>=1:
        df2.append(df.loc[df['C'] == x])

Unfortunately, that does not work (I don't get any output). My expected output (df2) would be:

index   A   B       C   D
2       foo two     2   4
6       foo one     6   12
7       foo three   7   14
Saraha
  • 144
  • 1
  • 12

1 Answers1

0

You just need to specify that you want df2to equal your append statement:

df2 = df2.append(df.loc[df['C'] == x])
Carsten
  • 2,765
  • 1
  • 13
  • 28