创建新df时,请不要覆盖原始df

时间:2019-10-23 17:48:17

标签: python pandas append

我有一个很大的df,结尾列是文件名。我想创建一个新的CSV连续文件名中所有带有'M'的文件。我已经设法完成了大部分工作,但是结尾的csv只有一行,其中包含在大型csv中找到的最后一个文件。我希望每一行都在新行上传输到csv。

我已经尝试了df.append的多种方式,但是没有任何运气。我看到了一些非常不同的方法,但是当感觉只需要进行少量调整时,它就需要更改我的所有代码

path = '.../files/'

big_data = pd.read_csv('landmark_coordinates.csv', sep=',', skipinitialspace=True) #open big CSV as a DF

#put photos into a male array based on the M character that appears in the filename

male_files = [f for f in glob.glob(path + "**/*[M]*.??g", recursive=True)]

for each_male in male_files: #for all male files
       male_data = big_data.loc[big_data['photo_name'] == each_male] # extract their row of data from the CSV and put in a new dataframe
    # NEEDED: ON A NEW LINE! MUST APPEND. right now it just overwrites
        male_data.to_csv('male_landmark_coordinates.csv', index=False, sep=',') #transport new df to csv format

就像我说的那样,我需要确保每个文件都从新的一行开始。真的很感谢任何帮助,因为我感觉我是如此亲密!

1 个答案:

答案 0 :(得分:0)

每次调用df.to_csv都将覆盖csv。

male_data = pd.DataFrame()

for each_male in male_files: #for all male files
       male_data.append(big_data.loc[big_data['photo_name'] == each_male])


male_data.to_csv('male_landmark_coordinates.csv', index=False, sep=',') #transport new df to csv format