簡體   English   中英

Pandas:從系列創建 DataFrame

[英]Pandas: Creating DataFrame from Series

我當前的代碼如下所示——我正在導入一個 MAT 文件並嘗試從其中的變量創建一個 DataFrame:

mat = loadmat(file_path)  # load mat-file
Variables = mat.keys()    # identify variable names

df = pd.DataFrame         # Initialise DataFrame

for name in Variables:

    B = mat[name]
    s = pd.Series (B[:,1])

所以在循環中,我可以為每個變量創建一系列(它們是 arrays,有兩列 - 所以我需要的值在第 2 列中)

我的問題是我怎么把append串到dataframe? 我查看了文檔,但似乎沒有一個示例適合我正在嘗試做的事情。

以下是如何創建一個 DataFrame,其中每個系列都是一行

對於單個系列(導致單行數據幀):

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

對於具有相同索引的多個系列:

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)

對於可能具有不同索引的多個系列:

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()

要創建一個 DataFrame ,其中每個系列都是一個 column ,請參閱其他人的答案。 或者,可以創建一個 DataFrame,其中每個系列都是一行,如上所述,然后使用df.transpose() 但是,如果列具有不同的數據類型,則后一種方法效率低下。

不需要初始化一個空的 DataFrame(你甚至沒有這樣做,你需要pd.DataFrame()和括號)。

相反,要創建一個 DataFrame,其中每個系列都是一列,

  1. 列出系列、 series
  2. df = pd.concat(series, axis=1)水平連接它們

就像是:

series = [pd.Series(mat[name][:, 1]) for name in Variables]
df = pd.concat(series, axis=1)

現在有一個pandas.Series.to_frame方法:

Series.to_frame(name=NoDefault.no_default)

將系列轉換為 DataFrame。

參數

nameobject ,可選:傳遞的名稱應該代替系列名稱(如果有的話)。

退貨

DataFrame :系列的 DataFrame 表示。

例子

s = pd.Series(["a", "b", "c"], name="vals") s.to_frame()

我想另一種方法,可能更快,實現這一點是 1) 使用 dict comprehension 來獲得所需的 dict (即,取每個數組的第二列) 2) 然后使用pd.DataFrame直接從 dict 創建一個實例,而不對每個進行循環col 和 concat。

假設你的mat看起來像這樣(你可以忽略這個,因為你的mat是從文件加載的):

In [135]: mat = {'a': np.random.randint(5, size=(4,2)),
   .....: 'b': np.random.randint(5, size=(4,2))}

In [136]: mat
Out[136]: 
{'a': array([[2, 0],
        [3, 4],
        [0, 1],
        [4, 2]]), 'b': array([[1, 0],
        [1, 1],
        [1, 0],
        [2, 1]])}

然后你可以這樣做:

In [137]: df = pd.DataFrame ({name:mat[name][:,1] for name in mat})

In [138]: df
Out[138]: 
   a  b
0  0  0
1  4  1
2  1  0
3  2  1

[4 rows x 2 columns]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM