BhishanPoudel
BhishanPoudel

Reputation: 17164

Pandas one-liner to join series elements

I was playing with pandas methods and encountered an issue. Can I join the elements of pandas series with comma?

MWE

j = {
  "locations": [
    {"name": "Seattle", "state": "WA"},
    {"name": "New York", "state": "NY"},
    {"name": "Bellevue", "state": "WA"},
    {"name": "Olympia", "state": "WA"}
  ]
}

df = pd.DataFrame(j['locations'])
ans = df.query("state=='WA'")['name'].sort_values()[-2:]

ans = df.query("state=='WA'")['name'].sort_values()[-2:].pipe(str.join) # this is my attempt but it does not work

Required answer

'Olympia, Seattle'

# NOTE:
obviously I can do ', '.join(ser.values)
but I am looking for pipe method.

Upvotes: 2

Views: 46

Answers (2)

Chris
Chris

Reputation: 16162

import pandas as pd
j = {
  "locations": [
    {"name": "Seattle", "state": "WA"},
    {"name": "New York", "state": "NY"},
    {"name": "Bellevue", "state": "WA"},
    {"name": "Olympia", "state": "WA"}
  ]
}

df = pd.DataFrame(j['locations'])

ans = df.query("state=='WA'")['name'].sort_values()[-2:]
ans.pipe(', '.join)

Upvotes: 1

Georgina Skibinski
Georgina Skibinski

Reputation: 13397

You don't want to pipe join into data frame, but str.join the full dataframe instead:

ans = ', '.join(df.query("state=='WA'")['name'].sort_values().iloc[-2:].tolist())

Additionally - using iloc[-2:] instead of just [-2:] will be safer, cause you won't be relying then on index being numbers 0, 1, 2, 3, ....

Upvotes: 1

Related Questions