[英]Converting a pandas dataframe to a list of lists for input into an RNN
在 Python 中,我有一個用pandas.read_csv
導入的數據pandas.read_csv
,例如如下所示:
Cust_id| time_to_event_f |event_id |event_sub_id
1 100 5 2
1 95 1 3
1 44 3 1
2 99 5 5
2 87 2 2
2 12 3 3
數據按cust_id
和time_to_event_f
。 我正在嘗試將此數據幀轉換為維度[2,3,3]
的張量,以便對於每個客戶 ID,我都有一個time_to_event_f
、 event_id
和event_sub_id
的順序列表。 這個想法是將其用作張量流中 RNN 的輸入。 我正在關注本教程,所以我試圖以類似的格式獲取我的數據。
您可以通過設置Cust_id
索引然后堆疊將原始數據幀d
轉換為以客戶 ID 為中心的系列:
d.set_index('Cust_id').stack()
結果系列將如下所示:
Cust_id
1 time_to_event_f 100
event_id 5
event_sub_id 2
time_to_event_f 95
event_id 1
event_sub_id 3
time_to_event_f 44
event_id 3
event_sub_id 1
2 time_to_event_f 99
event_id 5
event_sub_id 5
time_to_event_f 87
event_id 2
event_sub_id 2
time_to_event_f 12
event_id 3
event_sub_id 3
dtype: int64
鑒於這種表示,您的任務很簡單: values
ndarray 並將其重塑為您的目標大小:
series.values.reshape([2, 3, 3])
該數組可以作為 tensorflow RNN 的輸入。 完整代碼如下:
import pandas as pd
from io import StringIO
s = StringIO("""
1 100 5 2
1 95 1 3
1 44 3 1
2 99 5 5
2 87 2 2
2 12 3 3
""".strip())
d = pd.read_table(s, names=['Cust_id', 'time_to_event_f', 'event_id', 'event_sub_id'], sep=r'\s+')
series = d.set_index('Cust_id').stack()
time_array = series.values.reshape([2, 3, 3])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.