【问题标题】:How to save a list of files names to CSV file in a FOR LOOP?如何将文件名列表保存到 FOR LOOP 中的 CSV 文件?
【发布时间】:2022-01-18 00:28:42
【问题描述】:

我有一个 CSV 文件,其中一列中列出了数据(ID),我通过 for 循环将扩展名添加到每个 ID,然后我想将 for 循环中新生成的列表保存到 CSV 文件中。查看代码。 CSV file Data

import pandas as pd

# list of extension for the EEG images
channels = ['_Ch_01', '_Ch_02', '_Ch_03', '_Ch_04', '_Ch_05', '_Ch_06', '_Ch_07', '_Ch_08', 
'_Ch_09', '_Ch_10', '_Ch_11', '_Ch_12', '_Ch_13', '_Ch_14', '_Ch_15', '_Ch_16', '_Ch_17', 
'_Ch_18', '_Ch_19']

# Restrive the ID of images 
df = pd.read_csv ("Data.csv")

# Select the EDF column and add an extension to each ID
for ext in channels:
    png = df['Data'].tolist()
    png_list = list(map(lambda orig_string: orig_string + ext + ".png", png))
    for files in png_list:
        if files.endswith(".png"):
        print(files)
        print(f"want to save all the {files} to csv file in one column")

谢谢!

【问题讨论】:

  • 试过pd.to_csv()?
  • 是的,我试过了,但它无法将数据写入 CSV 文件的列中,而只能写入循环中的最后一个值。
  • 有19个频道。您想要 19 个单独的 CSV 还是 1 个组合所有通道的 CSV 作为输出?
  • @CodeDifferent 1 CSV 组合为输出,例如。 000254545_Ch_01, 000254545_Ch_02..... 000254545_CH_019 在遍历 CSV 文件中的所有 ID 后,在 CSV 文件的一列中。

标签: python pandas list csv for-loop


【解决方案1】:

你甚至不需要为此循环:

channels = [f"_Ch{i:02}.png" for i in range(1, 20)]

# Cross-product of df['Data'] and channels
# Essentially repeat each row in df['Data'] 19 times, once for each channel
index = pd.MultiIndex.from_product([df['Data'], channels])

# Concatenate the two levels of the index and export
s = index.get_level_values(0) + index.get_level_values(1)
s.to_series().to_csv('Output.csv', index=None, header=None)

【讨论】:

    猜你喜欢
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2018-04-26
    • 1970-01-01
    相关资源
    最近更新 更多