使用列数据源如何获取行的索引?

时间:2017-10-10 14:27:36

标签: python pandas bokeh

我正在使用从CSV文件填充的pandas数据框,然后我使用Bokeh将该数据框转换为ColumnDataSource。

看起来像:

dataFrame = pandas.read_csv('somefile.CSV')
source = ColumnDataSource(dataFrame)

现在我拥有了所有列,我想进行基于行的计算。

例如:我有三列:

x, y, colour

可能会填充:

1, 2, blue
2, 5, red
1, 8, yellow

现在,当我搜索源时,我想在该行中更改一些关联变量,那么我该怎么做呢:

# how do i step through the source dictionary?
if source['colour'] == 'blue':
    # how do I get the current index, which is the row number
    # how do I change the x column value at the index(row) we retrieved
    source['x' index] = 2 

谢谢

2 个答案:

答案 0 :(得分:1)

如果您正在迭代数据,可以这样做:

dataFrame = pandas.read_csv('somefile.csv')
source = ColumnDataSource(dataFrame)

for index, colour in enumerate(source.data['colour']):
    if colour == 'blue':
        source.data['x'][index] = 2

或者,为避免遍历整个ColumnDataSource,您可以使用以下内容获取'blue'列中'colour'的第一个值的索引:

list(source.data['colour']).index('blue')

您可以将此作为编辑列x的索引,如下所示:

source.data['x'][list(source.data['colour']).index('blue')] = 2

以这种方式索引此列表只会为您提供值'blue'的第一个索引。如果您的ColumnDataSource中有多个'blue'出现与之关联的'x'值,则应该能够通过索引列表后的'colour'列进行迭代'blue'的最后一个索引:

list(source.data['colour'])[last_index+1:].index('blue')

当它正在搜索的列表不包含值index('blue')时,它所在的循环应该包含在try语句中,因为ValueError会抛出'blue'

答案 1 :(得分:0)

使用

func fetchImages(_ predicate:Date, completion:(_ array:[Image], _ arrayData:NSArray)->()){
    var arrData = [NSManagedObject]()
    var existingImages = [Image]()
    let request :NSFetchrequest<NSFetchrequestResult> = NSFetchrequest(entityName: "Photo")

    do {
        let results = try context?.fetch(request)
        var myImage = Image()
        if ((results?.count) != nil) {
            for result in results! {
                myImage.imageUrl = (resultat as! NSManagedObject).value(forKey:"url") as! String
                myImage.imageFileName = (resultat as! NSManagedObject).value(forKey:"imageFileName") as! String    
                existingImages.append(myImage)
                arrData.append(result as! NSManagedObject)
            }
        } else{
            print ("No photo.")
        }
        completion(existingImages, arrData as NSArray)

    } catch{
        print ("Error during CoreData request")
    }
}

source.x[source.color == 'blue'] = 2 是您要更改的系列,括号中的条件仅选择其为真的行。