2

I have a data set of news with 3 columns: lead_paragraph, _id, web_url.

The following code returns a row matching the id along with News lead_paragraph.

ds = pd.read_csv("nytimes.csv")
def item(id):
    return ds.loc[ds['_id'] == id]['lead_paragraph'].tolist()[0]

How to get web_url also with lead_paragraph in the list?

Got an error after trying one solution

return ds.loc[ds['_id'] == id], ['web_url', 'lead_paragraph']].tolist()
                                                             ^
SyntaxError: invalid syntax
8
  • 1
    df.loc[ds['_id'] == id], ['x', 'y', 'z']].tolist()[0] Commented Mar 28, 2019 at 20:42
  • return [ds['_id'] == id], ['lead_paragraph','web_url']].tolist()[0] Its giving syntax error @coldspeed Commented Mar 28, 2019 at 20:50
  • @ScottBoston syntax error Commented Mar 28, 2019 at 20:56
  • ` return ds.loc[ds['_id'] == id], ['lead_paragraph','web_url' ] ].tolist()[0] ` Syntax error again Commented Mar 28, 2019 at 21:00
  • Can you paste the full error to the question. Commented Mar 28, 2019 at 21:05

1 Answer 1

2

Use df.loc[row indexer, columns indexer],

df.loc[df['_id'] == id, ['web_url', 'lead_paragraph']].values[0].tolist()

Where row indexer is a boolean series and column indexer is a list of column labels.

Sign up to request clarification or add additional context in comments.

3 Comments

return ds.loc[ds['_id'] == id], ['lead_paragraph','web_url']].tolist()[0] its giving me syntax error
You are correct, there was an extra ] before the first comma.
Can i refer my whole code , so that you can see what i am trying to do

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.