我有一个很大的 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
就像我说的,我需要确保每个文件都从新行开始。非常感谢任何帮助,因为感觉我是如此接近!
最佳答案
每次调用 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
关于python - 通过循环原始 df 创建新 df 时停止覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58528418/