【问题标题】:How to create a loop or function for the logic for this list of lists如何为此列表列表的逻辑创建循环或函数
【发布时间】:2016-04-03 05:10:27
【问题描述】:

我有一个如下所示的数据集:

CustomerID  EventID EventType   EventTime
6           1        Facebook    42373.31586
6           2        Facebook    42373.316
6           3        Web         42374.32921
6           4        Twitter     42377.14913
6           5        Facebook    42377.40598
6           6        Web         42378.31245
  • CustomerID:与特定的相关联的唯一标识符 客户
  • EventID:关于特定在线活动的唯一标识符
  • EventType:与此记录关联的在线活动类型 (网络、Facebook 或 Twitter)
  • EventTime:此在线活动的日期和时间 地方。该值以自 1900 年 1 月 1 日以来的天数来衡量,分数表示一天中的特定时间。例如,在 2016 年 1 月 1 日午夜发生的事件的 EventTime 为 42370.00,而在 2016 年 1 月 1 日中午发生的事件的 EventTime 为 42370.50。

我已成功导入 CSV 并使用以下代码创建列表:

# Import Libraries & Set working directory
import csv

# STEP 1:  READING THE DATA INTO A PYTHON LIST OF LISTS
f = open('test1000.csv', "r") # Import CSV as file type
a = f.read() # Convert file type into string
split_list = a.split("\r") # Removes \r
split_list[0:5] # Viewing the list

# Convert from lists to 'list of lists'
final_list = []
for row in split_list:
    split_list = row.split(',') # Split list by comma delimiter
    final_list.append(split_list) 
print(final_list[0:5])

#CREATING INITIAL BLANK LISTS FOR OUTPUTTING DATA
legit = [] 
fraud = []

接下来我需要将每条记录分类到欺诈或合法列表中。根据以下参数,记录将被视为欺诈。因此,该记录将进入欺诈名单。

将行分配给欺诈列表的逻辑:CustomerID 在过去 4 小时内执行相同的 EventType。

例如,上面示例数据集中的第 2 行(事件 2)将被移至欺诈列表,因为事件 1 发生在过去 4 小时内。另一方面,事件 4 将进入合法列表,因为在过去 4 小时内没有发生的 Twitter 记录。

数据集按时间顺序排列。

【问题讨论】:

    标签: python python-2.7 ipython


    【解决方案1】:

    此解决方案按 CustomerIDEventType 分组,然后检查上一个事件时间是否发生在 (lt) 4 小时前 (4. / 24)。

    df['possible_fraud'] = (
        df.groupby(['CustomerID', 'EventType'])
          .EventTime
          .transform(lambda group: group - group.shift())
          .lt(4. / 24))
    
    >>> df
       CustomerID  EventID EventType    EventTime possible_fraud
    0           6        1  Facebook  42373.31586          False
    1           6        2  Facebook  42373.31600           True
    2           6        3       Web  42374.32921          False
    3           6        4   Twitter  42377.14913          False
    4           6        5  Facebook  42377.40598          False
    5           6        6       Web  42378.31245          False
    
    >>> df[df.possible_fraud]
       CustomerID  EventID EventType  EventTime possible_fraud
    1           6        2  Facebook  42373.316           True
    

    【讨论】:

    • 测试时遇到问题。我可以看到您使用的完整代码吗? Gettng 错误:AttributeError: 'list' object has no attribute 'groupby'
    • df 通常表示 pandas DataFrame。我只是用df = pd.read_clipboard() 复制了您在帖子顶部的表格。你可能想试试pd.read_csv(filename)
    • 谢谢你。抱歉,现在又遇到另一个错误:AttributeError: 'list' object has no attribute 'groupby'
    • 同样的错误。你应该有一个数据框,而不是一个列表。
    • 非常感谢。现在一切都与此一致。我不认为它抓住了所有这些。我在 100 行的样本上运行了这个,然后目视检查了一些,发现有很多缺失。 sampledata
    【解决方案2】:

    当然,基于 pandas 的解决方案似乎更聪明,但这里是使用插入字典的示例。

    PS尽量自己进行输入输出

    #!/usr/bin/python2.7
    
    sample ="""
    6           1        Facebook    42373.31586
    6           2        Facebook    42373.316
    6           3        Web         42374.32921
    6           4        Twitter     42377.14913
    5           5        Web         42377.3541
    6           6        Facebook    42377.40598
    6           7        Web         42378.31245
    """
    
    last = {} # This dict will contain recent time 
    #values of events by client ID, for ex.: 
    #{"6": {"Facebook": 42373.31586, "Web": 42374.32921}}
    
    legit = []
    fraud = []
    
    for row in sample.split('\n')[1:-1:]:
        Cid, Eid, Type, Time = row.split()
        if Cid not in last.keys():
            legit.append(row)
            last[Cid] = {Type: Time}    
            row += '\tlegit'
        else:   
            if Type not in last[Cid].keys():
                legit.append(row)
                last[Cid][Type] = Time
                row += '\tlegit'
            else:
                if float(Time) - float(last[Cid][Type]) > (4. / 24):
                    legit.append(row)
                    last[Cid][Type] = Time
                    row += '\tlegit'
                else:
                    fraud.append(row)
                    row += '\tfraud'
        print row
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多