首页 > 解决方案 > 如果找到特定值,如何将数据框行附加到列表中?

问题描述

我正在尝试将包含特定 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”的列表?

标签: pythonpandaslistdataframeloops

解决方案


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

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

推荐阅读