1

我正在使用基于标签的索引功能loc来搜索对象的值"UN"在列列表中的所有标签,即 list "columns",但是在这段代码中,只要在第一个索引处loc找不到"UN",它就会在那之后停止,仅打印出第一个索引。

columns=["median","age","capital"]  # this is the list of columns

recent_grads是我的数据框。

for column in columns:
    recent_grads.loc[0:172 == 'UN',column]

'median'栏目

recent_grads["median"]

0        NaN
1      75000
2      73000
3      70000
4      65000
5      65000
6         UN
7      62000
8      60000
9      60000
10     60000
11     60000
12     60000
13     60000
14     58000
15     57100
16     57000
17     56000
18     54000
19     54000
20     53000
21     53000
22     52000
23     52000
24     51000
25     50000
26     50000
27     50000
28     50000
29     50000
       ...  
143    32000
144    32000
145    31500
146    31000
147    31000
148    31000
149    30500
150    30000
151    30000
152    30000
153    30000
154    30000
155    30000
156    30000
157    30000
158    29000
159    29000
160    29000
161    29000
162    28000
163    28000
164    28000
165    27500
166    27000
167    27000
168    26000
169    25000
170    25000
171    23400
172    22000
Name: median, Length: 173, dtype: object

至于我的代码的输出:

recent_grads.loc[0:172 == 'UN',"median"]

输出:

0    NaN
Name: median, dtype: object

关于选择一些随机起始索引

recent_grads.loc[3:172 == ['UN'],"median"]

输出不同:

Series([], Name: median, dtype: object)
4

2 回答 2

1

我认为您需要在前 172 条记录的列中搜索“UN”,如果是这样:

# returns a dataframe
df.head(172).filter(df[column] == 'UN')

文档:https ://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html#pandas.DataFrame.filter

更新:

如果你想使用loc,很简单:

df.head(172).loc[df[column] == 'UN']

关于已接受的答案,这不会将 a 转换为dataframe创建新对象的列表,并且可能会占用更多内存,尤其是当您的数据很大时。因此,这种原生 Dataframe 方法更有效。

于 2019-01-04T10:08:50.953 回答
1

如果你想要“联合国”标签:

利用 :

list_of_index=list(recent_grads[recent_grads['median'].str.contains('UN',na=False)].index)

或者 :

list_of_index = list(recent_grads.loc[recent_grads['median']=='UN'].index)

在哪里 :

recent_grads.loc[recent_grads['median']=='UN'] 

查找包含的行UN

于 2019-01-04T11:34:11.110 回答