如何从Pandas DataFrame的每一行中选择特定的列? [英] How can I select a specific column from each row in a Pandas DataFrame?
问题描述
我有一个采用以下格式的DataFrame:
I have a DataFrame in this format:
a b c
0 1 2 3
1 4 5 6
2 7 8 9
3 10 11 12
4 13 14 15
和类似这样的数组,其列名称为:
and an array like this, with column names:
['a', 'a', 'b', 'c', 'b']
,我希望提取数据数组,每行一个值.列名称数组指定我要从每一行中选择哪一列.在这里,结果将是:
and I’m hoping to extract an array of data, one value from each row. The array of column names specifies which column I want from each row. Here, the result would be:
[1, 4, 8, 12, 14]
这是否可以作为对Pandas的单个命令,还是需要迭代?我尝试使用索引
Is this possible as a single command with Pandas, or do I need to iterate? I tried using indexing
i = pd.Index(['a', 'a', 'b', 'c', 'b'])
i.choose(df)
但是我遇到了段错误,由于缺少文档,所以无法诊断.
but I got a segfault, which I couldn’t diagnose because the documentation is lacking.
推荐答案
You could use lookup
, e.g.
>>> i = pd.Series(['a', 'a', 'b', 'c', 'b'])
>>> df.lookup(i.index, i.values)
array([ 1, 4, 8, 12, 14])
如果需要,其中i.index
可能与range(len(i))
不同.
where i.index
could be different from range(len(i))
if you wanted.
这篇关于如何从Pandas DataFrame的每一行中选择特定的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!