代码之家  ›  专栏  ›  技术社区  ›  Gayatri

如何在dataframe中获取给定值的行数和列数

  •  0
  • Gayatri  · 技术社区  · 7 年前

    Image of CSV

    我在数据库中有一个blob(CSV)。我准备了一个字符串缓冲区并创建了一个panda数据帧。CSV文件没有特定列的列名,并且某些列名会重复。

    例如:如果需要获取 B5 = search_row E2 = search_column . ie E5 = value_to_be_fetched .

    我只有文本值 search_row search_column . 如何将行索引查找为 B5 和列索引为 E2 ? 以及获取值 E5=要提取的值 .

    1 回复  |  直到 7 年前
        1
  •  2
  •   jezrael    7 年前

    If值 search_row search_column 在所有数据使用中都是唯一的 np.where 对于位置和选择方式 DataFrame.iloc :

    df = pd.DataFrame({'A':list('abcdef'),
                       'B':[4,5,4,5,500,4],
                       'C':[7,8,9,4,2,3],
                       'D':[1,300,5,7,1,0],
                       'E':[5,3,6,9,2,4],
                       'F':list('aaabbb')}, index = [1] * 6)
    df.columns = ['A'] * 6
    print (df)
       A    A  A    A  A  A
    1  a    4  7    1  5  a
    1  b    5  8  300  3  a
    1  c    4  9    5  6  a
    1  d    5  4    7  9  b
    1  e  500  2    1  2  b
    1  f    4  3    0  4  b
    
    a = np.where(df == 500)[0]
    b = np.where(df == 300)[1]
    print (a)
    [4]
    print (b)
    [3]
    
    c = df.iloc[a[0],b[0]]
    print (c)
    1
    

    但如果可以复制值,请仅选择第一次出现,因为 np。哪里 使用返回数组 length > 1 :

    a = np.where(df == 5)[0]
    b = np.where(df == 2)[1]
    print (a)
    [0 1 2 3]
    print (b)
    [2 4]
    
    c = df.iloc[a[0],b[0]]
    print (c)
    7
    

    a = np.where(df == 2)[0]
    b = np.where(df == 5)[1]
    print (a)
    [4 4]
    print (b)
    [4 1 3 1]
    
    c = df.iloc[a[0],b[0]]
    print (c)
    2