如何在 Pandas 数据框中按名称选择行列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34236317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select a list of rows by name in Pandas dataframe?
提问by upendra
I am trying to extract rows from a Pandas dataframe using a list but it can't be done. Here is an example
我正在尝试使用列表从 Pandas 数据框中提取行,但无法完成。这是一个例子
# df
alleles chrom pos strand assembly# center protLSID assayLSID
rs#
TP3 A/C 0 3 + NaN NaN NaN NaN
TP7 A/T 0 7 + NaN NaN NaN NaN
TP12 T/A 0 12 + NaN NaN NaN NaN
TP15 C/A 0 15 + NaN NaN NaN NaN
TP18 C/T 0 18 + NaN NaN NaN NaN
test = ['TP3','TP12','TP18']
df.select(test)
This is what I was trying to do with just element of the list and I am getting this error TypeError: 'Index' object is not callable
. What am I doing wrong?
这就是我试图对列表中的元素进行的操作,但出现此错误TypeError: 'Index' object is not callable
。我究竟做错了什么?
采纳答案by Akavall
You can use df.loc[['TP3','TP12','TP18']]
您可以使用 df.loc[['TP3','TP12','TP18']]
Here is a small example:
这是一个小例子:
In [26]: df = pd.DataFrame({"a": [1,2,3], "b": [3,4,5], "c": [5,6,7]})
In [27]: df.index = ["x", "y", "z"]
In [28]: df
Out[28]:
a b c
x 1 3 5
y 2 4 6
z 3 5 7
[3 rows x 3 columns]
In [29]: df.loc[["x", "y"]]
Out[29]:
a b c
x 1 3 5
y 2 4 6
[2 rows x 3 columns]
回答by Joe T. Boka
You can select the rows by position:
您可以按位置选择行:
df.iloc[[0,2,4], :]