python - 将 Pandas 数据框转换为列表列表以输入到 RNN

标签 python pandas tensorflow deep-learning recurrent-neural-network

在 Python 中,我有一个使用 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_idevent_sub_id。这个想法是将其用作 tensorflow 中 RNN 的输入。我正在关注 this tutorial所以我试图以类似的格式获取我的数据。

最佳答案

您可以通过设置 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 并将其 reshape 为您的目标大小:

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

关于python - 将 Pandas 数据框转换为列表列表以输入到 RNN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46764464/

相关文章:

python - Tensorflow ctc_loss_calculator : No valid path found

python - 保存和加载模型的 Keras 架构不同

python - 机器学习中如何处理缺失数据?

pandas - 跨多索引的二元运算广播

python - TensorFlow:使用不同的损失函数恢复训练

python - 如何在 VS Code 中启用 pyspark 和 numpy 的方法建议?

python - 如何从切片对象中提取第一个 int

Tensorflow:使用批量归一化会导致验证损失和准确性较差(不稳定)

tensorflow - 在 Tensorboard 中使用 tf.name_scope 和 Tensorflow Estimator

python:验证函数参数