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

Jupyter Pandas数据帧-读取列值

  •  1
  • AlvinfromDiaspar  · 技术社区  · 8 年前

    我有一段python代码,用于读取给定行的SQL列的值。下面的代码段只是在数据帧上下文中遍历列,并将数值附加到数组中。

    如果我打印出每列的值,输出看起来是正确的。然而,如果我打印出最终的数组,那么我会看到奇怪的格式(元数据)。

    values = []
    for i in range(len(columns)):
            val = df[columns[i]];        
            values.append(val)
            #print(values) // this prints out the correct numeric value.
    
        #print(values) // but this prints out the array with the weird format.
    

    奇怪的/元数据输出如下所示:

    [0    0
    Name: colname1, dtype: int64, 0    8
    Name: colname2, dtype: int64, 0    0
    Name: colname3, dtype: int64, 0    0
    Name: colname4, dtype: int64, 0    0
    Name: colname5, dtype: int64, 0    0
    Name: colname6, dtype: int64, 0    0
    Name: colname7, dtype: int64, 0    0
    Name: colname8, dtype: int64, 0    0
    Name: colname9, dtype: int64, 0    0
    Name: colname10, dtype: int64, 0    1
    Name: colname11, dtype: int64, 0    0
    Name: colname12, dtype: int64]
    

    当我清楚地附加了数值时,为什么我会看到所有这些元数据?

    注意,数据帧是通过pd创建的。read\u sql\u查询调用。

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

    我认为您需要将值转换为 numpy array ,转置并转换为 list :

    df = pd.DataFrame({
        'A': ['a','e','g'],
        'B': list(range(3))
    })
    print (df)
       A  B
    0  a  0
    1  e  1
    2  g  2
    
    L = df.values.T.tolist()
    print (L)
    [['a', 'e', 'g'], [0, 1, 2]]
    

    如果需要循环缓慢的解决方案转换 Series 列表 :

    values = []
    for i in range(len(columns)):
            val = df[columns[i]];        
            values.append(val.tolist())
    

    如果只有一行 DataFrame 或者需要在 df 使用 iloc 按位置选择 系列 然后转换为 列表 :

    df = pd.DataFrame({
        'A': [0],
        'B': [3],
        'C' :[1]   
    })
    print (df)
       A  B  C
    0  0  3  1
    
    L = df.values.T.tolist()
    print (L)
    [[0], [3], [1]]
    
    #select first row
    L1 = df.iloc[0].tolist()
    print (L1)
    [0, 3, 1]
    

    df = pd.DataFrame({
        'A': ['a','e','g'],
        'B': list(range(3))
    },index=list('def'))
    print (df)
       A  B
    d  a  0
    e  e  1
    f  g  2
    
    #select by index name
    L1 = df.loc['f'].tolist()
    print (L1)
    ['g', 2]
    
    #select by position of row
    L1 = df.iloc[2].tolist()
    print (L1)
    ['g', 2]