如何读取多个csv并将特定列中包含特定值的单元格附加到pandas python中的新csv中

问题描述 投票:-1回答:1

我想使用pandas在python中进行编码。

我在文件夹中有多个csvs,具有相同列行中的不同值

我必须读取该文件夹中的每个.csv文件,读取'break'列,如果值= 1,则将其写入并附加到新的csv中,否则什么也不做。

我该如何实现?

我是编程和python的新手。

python python-3.x pandas csv read-write
1个回答
0
投票
import os
import pandas as pd
df = pd.DataFrame()

""" 
Gets all csvs from your folder given that you are already in the folder 
where you want to pull the files from. 
Otherwise, refer to the os library (i.e. using os.path.join)
"""
for file_name in os.listdir():
   if file_name.endswith('.csv'): # If the file is a csv
      temp_df = pd.read_csv(file_name)  

      # Get only rows that have the "break == 1"
      df = df.append(temp_df[temp_df['break'] == 1]) 

© www.soinside.com 2019 - 2024. All rights reserved.