gpt4 book ai didi

python - pandas dflocate仅保留第一项

转载 作者:行者123 更新时间:2023-11-30 22:43:43 25 4
gpt4 key购买 nike

我想根据同一行中某一列中的值获取另一列的值。

示例:

对于商家 id = '123',我想检索商家名称

df:

biz_id  biz_name
123 chew
456 bite
123 chew

代码:

df['biz_name'].loc[df['biz_id'] == 123]

返回我:

chew
chew

如何获取 1 个字符串格式的 'chew' 值?

最佳答案

您可以使用ilociat选择系列的第一个值:

print (df.loc[df['biz_id'] == 123, 'biz_name'].iloc[0])
chew

或者:

print (df.loc[df['biz_id'] == 123, 'biz_name'].iat[0])
chew

使用查询:

print (df.query('biz_id == 123')['biz_name'].iloc[0])
chew

或者选择列表numpy数组中的第一个值:

print (df.loc[df['biz_id'] == 123, 'biz_name'].tolist()[0])
chew

print (df.loc[df['biz_id'] == 123, 'biz_name'].values[0])
chew

时间:

In [18]: %timeit (df.loc[df['biz_id'] == 123, 'biz_name'].iloc[0])
1000 loops, best of 3: 399 µs per loop

In [19]: %timeit (df.loc[df['biz_id'] == 123, 'biz_name'].iat[0])
The slowest run took 4.16 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 391 µs per loop

In [20]: %timeit (df.query('biz_id == 123')['biz_name'].iloc[0])
The slowest run took 4.39 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 1.75 ms per loop

In [21]: %timeit (df.loc[df['biz_id'] == 123, 'biz_name'].tolist()[0])
The slowest run took 4.18 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 384 µs per loop

In [22]: %timeit (df.loc[df['biz_id'] == 123, 'biz_name'].values[0])
The slowest run took 5.32 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 370 µs per loop

In [23]: %timeit (df.loc[df.biz_id.eq(123).idxmax(), 'biz_name'])
1000 loops, best of 3: 517 µs per loop

关于python - pandas dflocate仅保留第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41690769/

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