【发布时间】: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