【问题标题】:How to append a dataframe row to a list if a specific value is found?如果找到特定值,如何将数据框行附加到列表中?
【发布时间】:2021-11-08 09:46:01
【问题描述】:

我正在尝试将包含特定 DateTime 值的所有行添加到列表中,然后打印所述列表。我遍历数据框中的所有行,在列中查找特定值。如果出现该值,我想将该特定行添加到列表中。

代码:

with open('Layer1.csv', newline = '') as csvfile2:
        df = pd.read_csv('Layer1.csv')

        AudioMothIDs = getID()
        AudioMothIDs.remove('NA')

        csv_reader = csv.reader(csvfile2)
        
        for row in csv_reader:
            orig_list = []
            #Iterates through each unique ID
            for x in AudioMothIDs:
                ID_df = df[df['AudioMothID'] == x]
          
                #Iterates through all rows in the ID dataframe
                for index, rows in ID_df.iterrows():
                    #Searches for a specific DateTime within the StartDateTime column
                    if '16.06.2019 15:00' in ID_df.StartDateTime.values:
                        #Attempts to add rows with the specific DateTime to a list
                        current_list = [rows.AudioMothID,rows.StartDateTime]
                        orig_list.append(current_list)
            print(orig_list)

追加 rows.AudioMothID 和 rows.StartDatetime 会将 ID 内的所有行追加到列表中,而不仅仅是 StartDateTime 列中具有“16.06.2019 15:00”的行。我也尝试过使用 ID_df.iloc[index] 类似地添加所有行,而不是只添加包含指定字符串的行。

如何仅将行附加到 StartDateTime 列中包含“16.06.2019 15:00”的列表?

【问题讨论】:

    标签: python pandas list dataframe loops


    【解决方案1】:

    我认为你做了很多不必要的步骤,例如读取 csv 文件两次,遍历每一行,然后遍历每个 ID。

    让我们简单地使用pandas

    # read dataframe using pandas
    df = pd.read_csv('Layer1.csv')
    
    # filter for date, select specific columns and convert to list
    df[df.StartDateTime == '16.06.2019 15:00'][[df.AudioMothID, df.StartDateTime]].values.tolist()
    
    

    [编辑] 添加以解决您的 cmets:

    1. 如何选择某个小时内的值
    # ensure date column is in the right format
    df['StartDateTime'] = pd.to_datetime(df['StartDateTime'])
    
    # filter by hour of date
    df[df.StartDateTime.dt.hour == 15]
    
    
    1. 如何对每个小时和每个 ID 进行随机抽样
    # ensure date column is in the right format
    df['StartDateTime'] = pd.to_datetime(df['StartDateTime'])
    
    # round date column to nearest hour
    df['StartDateTime_nearest_hour'] = df['StartDateTime'].dt.round('H')
    
    # randomly sample 1 by each hour of each day and ID
    df.groupby(['AudioMothID', 'StartDateTime_nearest_hour'].sample(n=1)
    
    # if you want to sample an hour of a random day instead:
    df['StartDateTime_hour'] = df['StartDateTime'].dt.hour
    df.groupby(['AudioMothID', 'StartDateTime_hour'].sample(n=1)
    

    【讨论】:

    • 感谢您的回答!相反,如果我想在每个 ID 内添加某个小时内的值……例如。为每个 ID 附加 15:00 小时内的所有值。 ...我该怎么做呢?此外,我稍后想从 15:00 小时内的所有行列表中为每个 ID 随机选择一个值。我正在尝试使用分层随机抽样为一天中的每个小时每小时生成 1 个随机行,每个 ID 总共 24 行。
    【解决方案2】:

    你的代码可以被压缩成更符合熊猫的习惯。可能是这样的:

    # Load CSV into a pandas DataFrame, no need for csv.reader or with open()
    df = pd.read_csv('Layer1.csv')
    
    # Copy all rows with the desired StartDateTime as a new DataFrame
    res = df[df['StartDateTime'] == '16.06.2019 15:00'].copy()
    
    print(res)
    

    【讨论】:

      猜你喜欢
      • 2019-05-24
      • 2019-12-30
      • 2022-01-17
      • 2021-10-26
      • 2021-10-13
      • 1970-01-01
      • 2019-10-12
      • 1970-01-01
      • 2021-11-23
      相关资源
      最近更新 更多