gpt4 book ai didi

Python pandas 从其他列返回值

转载 作者:太空宇宙 更新时间:2023-11-03 12:43:44 24 4
gpt4 key购买 nike

我有一个文件“specieslist.txt”,其中包含以下信息:

Bacillus,genus
Borrelia,genus
Burkholderia,genus
Campylobacter,genus

现在,我希望 python 在第一列(在此示例中为“弯曲杆菌”)中查找变量并返回第二列(“属”)的值。我写了下面的代码

import csv
import pandas as pd

species_import = 'Campylobacter'
df = pd.read_csv('specieslist.txt', header=None, names = ['species', 'level'] )
input = df.loc[df['species'] == species_import]
print (input['level'])

但是,我的代码返回太多,而我只想要“属”

3    genus
Name: level, dtype: object

最佳答案

您可以通过ia 选择系列的第一个值:

species_import = 'Campylobacter'
out = df.loc[df['species'] == species_import, 'level'].iat[0]
#alternative
#out = df.loc[df['species'] == species_import, 'level'].values[0]
print (out)
genus

如果没有匹配的值并且返回空系列,更好的解决方案 - 它返回不匹配:

@jpp comment
This solution is better only when you have a large series and the matched value is expected to be near the top

species_import = 'Campylobacter'
out = next(iter(df.loc[df['species'] == species_import, 'level']), 'no match')
print (out)
genus

编辑:

来自评论的想法,感谢@jpp:

def get_first_val(val):
try:
return df.loc[df['species'] == val, 'level'].iat[0]
except IndexError:
return 'no match'

print (get_first_val(species_import))
genus

print (get_first_val('aaa'))
no match

编辑:

df = pd.DataFrame({'species':['a'] * 10000 + ['b'], 'level':np.arange(10001)})

def get_first_val(val):
try:
return df.loc[df['species'] == val, 'level'].iat[0]
except IndexError:
return 'no match'


In [232]: %timeit next(iter(df.loc[df['species'] == 'a', 'level']), 'no match')
1.3 ms ± 33.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [233]: %timeit (get_first_val('a'))
1.1 ms ± 21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)



In [235]: %timeit (get_first_val('b'))
1.48 ms ± 206 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [236]: %timeit next(iter(df.loc[df['species'] == 'b', 'level']), 'no match')
1.24 ms ± 10.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

关于Python pandas 从其他列返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52740125/

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