python - 如果找到特定值,如何将数据框行附加到列表中?
问题描述
我正在尝试将包含特定 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”的列表?
解决方案
你的代码可以被压缩成更符合熊猫的习惯。也许是这样的:
# 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)
推荐阅读
- java - Android Manifest 怎么会再次合并?
- python - 使用来自另一个数据帧的相应数据填充列值(合并??)
- sql - 如何在 SQL 中选择层次关系的顶层?
- javascript - Openlayers:如何使用 onClick 识别点?
- powerbi - 从列值中提取子字符串
- reactjs - React - 通过迭代创建多个组件是否效率低下?
- java - 当我使用 AES 加密或解密文件时,文件末尾有奇怪的字符,这可能是缓冲区问题还是 AES 问题?
- c++ - 将子字符串提取到最后一个分隔符 C++
- python - 如何在python中制作数据类型整数
- xml - 是否可以在kafka中发布xml?