【问题标题】:How can I iterate through Data Frame and create folders as columns in the df and subfolders as rows in the df?如何遍历数据框并将文件夹创建为 df 中的列,将子文件夹创建为 df 中的行?
【发布时间】:2021-10-06 15:09:00
【问题描述】:

这是我得到的代码:

prod_lst = getprod()
prod_df = pd.DataFrame(prod_lst, columns = ['Client'])
for i, j in prod_df.iterrows():
  print(i,j)
  path = '../models/' + i + '/' + j
  isExist = os.path.exists(path)
  if not isExist:
      os.makedirs(path)

'''

  Client

0 OTT

1 DVD

2 OTV

'''

需要类似目录

''' 客户

OTT

DVD

OTV

'''

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    DataFrame.iterrows 产生“(索引,系列)对。”这意味着 j 是一系列值,表示 DataFrame 中的行。要从 Client 访问特定值,我们需要从系列中选择值:

    import os
    import pandas as pd
    
    # Sample DF
    prod_df = pd.DataFrame([['OTT'], ['DVD'], ['OTV']], columns=['Client'])
    # Column to Select
    col = 'Client'
    # Iterate over rows
    for idx, row in prod_df.iterrows():
        path = f'../models/{col}/{row[col]}'
        exists = os.path.exists(path)
        if not exists:
            os.makedirs(path)
    

    或者,如果我们不需要行中的所有值,我们可以只迭代 Client 列:

    import os
    import pandas as pd
    
    # Sample DF
    prod_df = pd.DataFrame([['OTT'], ['DVD'], ['OTV']], columns=['Client'])
    # Loop Over Just the Client Column
    col = 'Client'
    # Loop Over values in just the column
    for value in prod_df[col]:
        path = f'../models/{col}/{value}'
        exists = os.path.exists(path)
        if not exists:
            os.makedirs(path)
    

    文件夹创建逻辑也可以用Path.mkdir from pathlib来简化:

    from pathlib import Path
    
    import pandas as pd
    
    # Sample DF
    prod_df = pd.DataFrame([['OTT'], ['DVD'], ['OTV']], columns=['Client'])
    # Loop Over Just the Client Column
    col = 'Client'
    for value in prod_df[col]:
        Path(f'../models/{col}/{value}').mkdir(parents=True, exist_ok=True)
    

    【讨论】:

      【解决方案2】:

      我找到了一种有效的方法;不确定这是否是最佳做法。

      for value, rows in prod_df.itertuples():
          
          path = '../models/' + prod_df.columns[0] + '/' + rows
          isExist = os.path.exists(path)
          if not isExist:
              os.makedirs(path)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-03
        • 2012-10-26
        • 1970-01-01
        • 2013-09-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多