user7830303
user7830303

Reputation:

Python Pandas - adding rows to an empty Dataframe

I am reading this frame from file:

 df = pd.read_csv('playlist.csv')

and fetching all values under column 'track':

 tracks = df['track'].tolist()

then I have a new_df with the same order of columns as 'playlist.csv':

new_df = pd.DataFrame(columns=['artist','track', 'value'])

and, given other_tracks = ['Once', 'Jeremy'], I would to add the entire row of some tracks to the new_df

for track in tracks:
    if track in other_tracks:
         row = df[df['track']==track]

how do I do it?

is there a simple way of doing this?

Upvotes: 2

Views: 922

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210832

IIUC you don't need to loop, you can simply use boolean indexing:

new_df = df.loc[df['track'].isin(other_tracks)]

Upvotes: 3

Related Questions