Pandas 将行作为列添加到表中

Pandas 将行作为列添加到表中,pandas,Pandas,我正试图通过将所有行转换为列来更改我的数据集 567 8910 需要根据需要进行更改 56778910 当然,对于不同的标题,有什么建议吗???使用numpy的重塑功能: import pandas as pd import numpy as np df = pd.DataFrame([[5, 6, 7],[8, 9, 10]]) nparray = np.array(df.iloc[:,:]) x = np.reshape(nparray, -1) df = pd.DataFrame(x)

我正试图通过将所有行转换为列来更改我的数据集

  • 567
  • 8910
  • 需要根据需要进行更改

  • 56778910

  • 当然,对于不同的标题,有什么建议吗???

    使用numpy的重塑功能:

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame([[5, 6, 7],[8, 9, 10]])
    nparray = np.array(df.iloc[:,:])
    x = np.reshape(nparray, -1)
    df = pd.DataFrame(x) #to convert back to a dataframe
    
    您还可以使用reduce()

    使用
    pd.DataFrame([df.values.flatte()])
    如下所示:

    In [18]: df
    Out[18]:
       0  1   2
    0  5  6   7
    1  8  9  10
    
    In [19]: pd.DataFrame([df.values.flatten()])
    Out[19]:
       0  1  2  3  4   5
    0  5  6  7  8  9  10
    
    说明:

    df.values
    返回
    numpy.ndarray

    In [18]: df.values
    Out[18]:
    array([[ 5,  6,  7],
           [ 8,  9, 10]], dtype=int64)
    
    In [19]: type(df.values)
    Out[19]: numpy.ndarray
    
    和numpy数组具有
    .flant()
    方法:

    In [20]: df.values.flatten?
    Docstring:
    a.flatten(order='C')
    
    Return a copy of the array collapsed into one dimension.
    
    In [21]: df.values.flatten()
    Out[21]: array([ 5,  6,  7,  8,  9, 10], dtype=int64)
    
    Pandas.DataFrame
    构造函数需要行的列表/数组:

    如果我们尝试这样做:

    In [22]: pd.DataFrame([ 5,  6,  7,  8,  9, 10])
    Out[22]:
        0
    0   5
    1   6
    2   7
    3   8
    4   9
    5  10
    
    Pandas认为这是一个行列表,其中每行有一个元素

    因此,我将该数组括在方括号中:

    In [23]: pd.DataFrame([[ 5,  6,  7,  8,  9, 10]])
    Out[23]:
       0  1  2  3  4   5
    0  5  6  7  8  9  10
    
    这将被理解为一行6列。

    或仅在一行中:

    df = pd.DataFrame([[1,2,3],[4,5,6]])
    df.values.flatten()
    #out: array([1, 2, 3, 4, 5, 6])
    

    尝试使用NUMPY中的重塑函数如何将其转换回数据帧?只需调用DataFrame()函数。请看版本,谢谢。对于我的数据,我相信展平方法比重塑方法要简单一些。再次感谢。你能在回答中添加一个描述吗?谢谢,但阿利雷扎也发了同样的帖子。@BrandonA,我已经添加了一个解释-我希望它会更好now@achaud,没错,但我提前11秒给出了答案,所以我不知道Alireza Sohofi会提前给出同样的答案;-)@是的,现在好多了!非常感谢。我用你的扁平化方法,把它转换成熊猫数据文件,只是做了我的工作。你很受欢迎,如果答案有帮助,我会很感激如果你考虑“接受”它。
    df = pd.DataFrame([[1,2,3],[4,5,6]])
    df.values.flatten()
    #out: array([1, 2, 3, 4, 5, 6])