Python 使用loc替换/选择列中的值。熊猫
我正在使用基于标签的索引功能Python 使用loc替换/选择列中的值。熊猫,python,database,python-3.x,pandas,Python,Database,Python 3.x,Pandas,我正在使用基于标签的索引功能loc搜索列列表中对象值为“UN”的所有标签,即列表“列”,但在这段代码中,只要loc在第一个索引中没有找到“UN”,它就会停止,只打印出第一个索引 columns=["median","age","capital"] # this is the list of columns 最近的大学毕业生是我的数据框架 for column in columns: recent_grads.loc[0:172 == 'UN',column] 这是“中间值”列 re
loc
搜索列列表中对象值为“UN”
的所有标签,即列表“列”
,但在这段代码中,只要loc
在第一个索引中没有找到“UN”
,它就会停止,只打印出第一个索引
columns=["median","age","capital"] # this is the list of columns
最近的大学毕业生
是我的数据框架
for column in columns:
recent_grads.loc[0:172 == 'UN',column]
这是“中间值”
列
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)
我认为您需要在前172条记录的列中搜索“UN”,如果是这样的话:
# returns a dataframe
df.head(172).filter(df[column] == 'UN')
文件:
更新:
如果要使用loc
,请轻松:
df.head(172).loc[df[column] == 'UN']
对于已接受的答案,这不会将
数据帧
转换为列表,从而创建新对象,并且可能会占用更多内存,尤其是当数据较大时。因此,本机数据帧方法更有效 如果需要“UN”标签:
使用:
或:
其中:
recent_grads.loc[recent_grads['median']=='UN']
查找包含
UN
的行,提供示例数据和预期输出。不清楚需要什么,可能是最近的毕业生。loc[0:172,column]=“UN”
?0:172
表示什么?您所说的是什么意思,其中对象的值在列的列表中为“UN”?你能给我一个机会吗?好了!例子。检查@韦丹特里帕蒂如果我的答案是你所需要的,你可以选择它作为一个公认的答案。或者你可以告诉我如何改进它。谢谢。有没有办法使用loc函数来实现这一点?我正在尝试使用loc来实现它,然后在过滤器之后,我将用NaN替换“UN”。@Vedanttripath我已经更新了答案,我认为我的解决方案更好。谢谢,我能够理解并执行该操作。
list_of_index = list(recent_grads.loc[recent_grads['median']=='UN'].index)
recent_grads.loc[recent_grads['median']=='UN']