从 Pandas DataFrame 返回单个单元格值 [英] Return single cell value from Pandas DataFrame
本文介绍了从 Pandas DataFrame 返回单个单元格值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想问一个问题,这是这个线程的扩展:
I would like to ask an question that is an extension on this thread:
根据 Pandas 中列中的值从 DataFrame 中选择行.
该线程的代码如下:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})
print(df)
# A B C D
# 0 foo one 0 0
# 1 bar one 1 2
# 2 foo two 2 4
# 3 bar three 3 6
# 4 foo two 4 8
# 5 bar two 5 10
# 6 foo one 6 12
# 7 foo three 7 14
print(df.loc[df['D'] == 14])
这将产生以下结果:
A B C D
7 foo three 7 14
根据上面的代码,我怎样才能返回单个值"而不是一行.也就是说,我如何返回值 '7'
或值 'foo'
而不是整行?
Based on the code above, how can I return a single 'value' not a row. That is, how can I return the value '7'
or value 'foo'
as opposed to the entire row?
推荐答案
@JonahWilliams 很接近,这是一个可行的方案:
@JonahWilliams was close, here's a working one:
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
'B': 'one one two three two two one three'.split(),
'C': np.arange(8), 'D': np.arange(8) * 2})
print(df.loc[df['D'] == 14]['A'].index.values)
>>>[7]
print(df.loc[df['D'] == 14]['A'].values)
>>>['foo']
这篇关于从 Pandas DataFrame 返回单个单元格值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文