Pandas: Creating DataFrame from Series

前端 未结 3 1134
清酒与你
清酒与你 2020-12-29 01:36

My current code is shown below - I\'m importing a MAT file and trying to create a DataFrame from variables within it:

mat = loadmat(file_path)  # load mat-fi         


        
3条回答
  •  天命终不由人
    2020-12-29 01:58

    Here is how to create a DataFrame where each series is a row.

    For a single Series (resulting in a single-row DataFrame):

    series = pd.Series([1,2], index=['a','b'])
    df = pd.DataFrame([series])
    

    For multiple series with identical indices:

    cols = ['a','b']
    list_of_series = [pd.Series([1,2],index=cols), pd.Series([3,4],index=cols)]
    df = pd.DataFrame(list_of_series, columns=cols)
    

    For multiple series with possibly different indices:

    list_of_series = [pd.Series([1,2],index=['a','b']), pd.Series([3,4],index=['a','c'])]
    df = pd.concat(list_of_series, axis=1).transpose()
    

    To create a DataFrame where each series is a column, see the answers by others. Alternatively, one can create a DataFrame where each series is a row, as above, and then use df.transpose(). However, the latter approach is inefficient if the columns have different data types.

提交回复
热议问题