大熊猫相当于R的哪个()

use*_*394 15 python logical-operators which pandas

之前已经问过这个问题的变化,我仍然无法理解如何根据我想要设置的条件实际切片python系列/ pandas数据帧.

在R中,我要做的是:

df[which(df[,colnumber] > somenumberIchoose),]
Run Code Online (Sandbox Code Playgroud)

which()函数在数据框的列中查找大于somenumberIchoose的行的条目索引,并将其作为向量返回.然后,我使用这些行索引对数据帧进行切片,以指示我想在新表单中查看哪些数据帧行.

在python中有相同的方法吗?我已经看过枚举的引用,在阅读文档后我并不完全理解.我的示例为了获得行索引,现在看起来像这样:

indexfuture = [ x.index(), x in enumerate(df['colname']) if x > yesterday]  
Run Code Online (Sandbox Code Playgroud)

但是,我继续收到无效的语法错误.我可以通过循环遍历值,并自己手动进行搜索来破解解决方法,但这似乎非常非pythonic和低效.

枚举()究竟是做什么的?什么是在矢量中找到满足所需参数的值索引的pythonic方法?

注意:我正在使用Pandas作为数据帧

小智 12

我可能不清楚这个问题,但看起来响应比你想象的要容易:

使用pandas DataFrame:

df['colname'] > somenumberIchoose
Run Code Online (Sandbox Code Playgroud)

返回一个带有True/False值的pandas系列和DataFrame的原始索引.

然后,您可以在原始DataFrame上使用该布尔系列,并获取您要查找的子集:

df[df['colname'] > somenumberIchoose]
Run Code Online (Sandbox Code Playgroud)

应该够了.

http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing

  • `df[df['colname'] > somenumberIchoose].index` 与 R which() 函数相同 (2认同)

Dun*_*nes 5

我所知道的R你可能会更习惯使用numpy - 一种类似于MATLAB的科学计算软件包.

如果你想要一个数组的索引值可以被2整除,那么下面的代码就可以了.

arr = numpy.arange(10)
truth_table = arr % 2 == 0
indices = numpy.where(truth_table)
values = arr[indices]
Run Code Online (Sandbox Code Playgroud)

使用多维数组也很容易

arr2d = arr.reshape(2,5)
col_indices = numpy.where(arr2d[col_index] % 2 == 0)
col_values = arr2d[col_index, col_indices]
Run Code Online (Sandbox Code Playgroud)

  • +1 对于更接近 R 习语的解决方案。我也不喜欢把所有东西都变成熊猫数据框。 (2认同)