gpt4 book ai didi

python - Pandas one-liner 加入系列元素

转载 作者:行者123 更新时间:2023-12-04 08:42:31 26 4
gpt4 key购买 nike

我在玩 Pandas 方法时遇到了一个问题。
我可以用逗号加入 Pandas 系列的元素吗?
移动电源

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
必答
'Olympia, Seattle'

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

最佳答案

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)

关于python - Pandas one-liner 加入系列元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64486106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com