【发布时间】:2020-02-20 00:42:20
【问题描述】:
我有一个很大的 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
就像我说的,我需要确保每个文件都从新行开始。真的很感谢任何帮助,因为感觉就像我离得很近!
【问题讨论】:
-
@Efran 我的问题是另一个问题。我不想附加到现有的 CSV。我正在通过循环现有的 CSV 并选择某些文件来创建新的 CSV。我的问题在于覆盖,而不是创建 csv 本身。
-
male_data.to_csv(f'male_landmark_coordinates_{each_male}.csv', index=False, sep=',')? -
@QuangHoang 当我这样做时,每个文件的输出是许多单独的 csv 文件。我想要的只是一个 CSV 文件,上面包含 each_file 的所有输出