Tobitor
Tobitor

Reputation: 1508

How to get new pandas dataframe with certain columns and rows depending on list elements?

I have such a list:

l = ['A','B']

And such a dataframe df

Name x y
A 1 2
B 2 1
C 2 2

I now want to get a new dataframe where only the entries for Name and x which are included in l are kept.

new_df should look like this:

Name x
A 1
B 2

I was playing around with isin but did not solve this problem.

Upvotes: 1

Views: 35

Answers (3)

Amith Lakkakula
Amith Lakkakula

Reputation: 516

l = ['A','B']

def make_empty(row):
    print(row)
    for idx, value in enumerate(row):
        row[idx] = value if value in l else ''
    return row

df_new = df[df['Name'].isin(l) | df['x'].isin(l)][['Name','x']]
df_new.apply(lambda row: make_empty(row)

Output:
    Name x
0    A  
1    B  

Upvotes: 0

jezrael
jezrael

Reputation: 862911

Use DataFrame.loc with Series.isin:

new_df = df.loc[df.Name.isin(l), ["Name", "x"]]

Upvotes: 1

qmeeus
qmeeus

Reputation: 2402

This should do it:

# assuming Name is the index
new_df = df[df.index.isin(l)]
# if you only want column x
new_df = df.loc[df.index.isin(l), "x"]

simple as that

Upvotes: 1

Related Questions