我有一個巨大的字串(類似于名單可疑交易報告如下,但更大)。每列都給出了時間戳。
我想根據以下內容有效地將其轉換為表格格式(numpy 陣列或熊貓資料框或...)。
strs = ['time', 'stamp1', 'a', '1', 'b', '2', 'c', '3',
'time', 'stamp2', 'a', '11', 'b', '22', 'd', '4',
'time', 'stamp3', 'a', '111', 'b', '222', 'c', '333',
'time', 'stamp4', 'a', '1111', 'b', '2222', 'c', '3333', 'd', '444']
| 時間 | 一種 | 乙 | C | d |
|---|---|---|---|---|
| 郵票1 | 1 | 2 | 3 | |
| 郵票2 | 11 | 22 | 4 | |
| 圖章3 | 111 | 222 | 333 | |
| 圖章 4 | 1111 | 2222 | 3333 | 444 |
uj5u.com熱心網友回復:
你可以這樣做:
import pandas as pd
records = []
record = {strs[0]: strs[1]}
for key, value in zip(strs[2::2], strs[3::2]):
if key == "time":
records.append(record)
record = {key: value}
else:
record[key] = value
else:
records.append(record)
table = pd.DataFrame(records)
結果:
time a b c d
0 stamp1 1 2 3 NaN
1 stamp2 11 22 NaN 4
2 stamp3 111 222 333 NaN
3 stamp4 1111 2222 3333 444
或者通過生成器來做:
import pandas as pd
def records(lst):
record = {lst[0]: lst[1]}
for key, value in zip(lst[2::2], lst[3::2]):
if key == "time":
yield record
record = {key: value}
else:
record[key] = value
else:
yield record
table = pd.DataFrame(records(strs))
uj5u.com熱心網友回復:
我會首先將此串列作為字典處理,然后將字典轉換為pandasDataFrame。但首先您需要填寫缺失值,因為串列的大小需要相同才能創建資料框。我通過strs根據time字串的外觀將串列拆分為子串列來做到這一點。然后,我還通過從 0 開始對串列的所有其他值進行切片,然后將其傳遞給 aset以僅獲取唯一值來獲取列名。
然后我遍歷代表我們行的子串列串列,如果串列中沒有代表列的值,我添加它并給它一個NaN值。一旦子串列串列具有每列的所有值。然后我回圈遍歷它并將值分配給dict以創建資料幀。創建字典后,只需將其傳遞給from_dict將根據字典中的鍵值對創建列。
唯一的問題是列沒有按順序排列,所以我重新排序了它們。
strs = ['time', 'stamp1', 'a', '1', 'b', '2', 'c', '3',
'time', 'stamp2', 'a', '11', 'b', '22', 'd', '4',
'time', 'stamp3', 'a', '111', 'b', '222', 'c', '333',
'time', 'stamp4', 'a', '1111', 'b', '2222', 'c', '3333', 'd', '444']
# splitting the lists by the 'time' string since thats the start of a new row
col_names = set(strs[::2])
Lsub = []
L2 = []
for e in strs:
if e == 'time':
if Lsub:
L2.append(Lsub)
Lsub = [e]
else:
Lsub.append(e)
L2.append(Lsub)
#fill in missing values
for sublist in L2:
for col in col_names:
if col not in sublist:
sublist.extend([col, np.nan])
# create dictionary to assign values too
df_dict = {k: [] for k in col_names}
for x in L2:
for i, y in enumerate(x):
if i == 0:
continue
if x[i-1] in col_names:
df_dict[x[i-1]].append(y)
df = pd.DataFrame.from_dict(df_dict)
cols = ['time'] sorted([x for x in col_names if x != 'time'])
df = df[cols]
print(df)
這給出了這個輸出:
time a b c d
0 stamp1 1 2 3 NaN
1 stamp2 11 22 NaN 4
2 stamp3 111 222 333 NaN
3 stamp4 1111 2222 3333 444
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/369819.html
