從我的 for 回圈中,結果串列如下:
#These lists below are list types and in ordered/structured.
key=[1234,2345,2223,6578,9976]
index0=[1,4,6,3,4,5,6,2,1]
index1=[4,3,2,1,6,8,5,3,1]
index2=[9,4,6,4,3,2,1,4,1]
如何將它們全部合并到熊貓的表格中?下面是期待。
key | index0 | index1 | index2
1234 | 1 | 4 | 9
2345 | 4 | 3 | 4
... | ... | ... | ...
9967 | 1 | 1 | 1
我曾嘗試使用 pandas,但只是遇到了有關資料型別的錯誤。然后我將dtype設定為int64和int32,但仍然再次遇到有關資料型別的錯誤。
對于一個可選問題,我是否應該使用 SQL 從串列中類似的資料組裝一個表?我只是在使用 mySQL 學習 SQL,想知道它是否比使用 pandas 更方便用于記錄保存和持久存盤?
uj5u.com熱心網友回復:
只需使用 dict 并將其傳遞給pd.DataFrame:
dct = {
'key': pd.Series(key),
'index0': pd.Series(index0),
'index1': pd.Series(index1),
'index2': pd.Series(index2),
}
df = pd.DataFrame(dct)
輸出:
>>> df
key index0 index1 index2
0 1234.0 1 4 9
1 2345.0 4 3 4
2 2223.0 6 2 6
3 6578.0 3 1 4
4 9976.0 4 6 3
5 NaN 5 8 2
6 NaN 6 5 1
7 NaN 2 3 4
8 NaN 1 1 1
uj5u.com熱心網友回復:
這是另一種方式:
首先將資料加載到字典中:
d = dict(key=[1234,2345,2223,6578,9976],
index0=[1,4,6,3,4,5,6,2,1],
index1=[4,3,2,1,6,8,5,3,1],
index2=[9,4,6,4,3,2,1,4,1])
然后轉換為df:
df = pd.DataFrame({i:pd.Series(j) for i,j in d.items()})
輸出:
key index0 index1 index2
0 1234.0 1 4 9
1 2345.0 4 3 4
2 2223.0 6 2 6
3 6578.0 3 1 4
4 9976.0 4 6 3
5 NaN 5 8 2
6 NaN 6 5 1
7 NaN 2 3 4
8 NaN 1 1 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/441284.html
標籤:Python python-3.x 熊猫 数据框
