【问题标题】:Dynamically Splitting Rows in dataframe动态拆分数据框中的行
【发布时间】:2017-01-03 08:05:30
【问题描述】:

我需要获取一个 CSV 文件并拆分行并将它们级联。输入 CSV 可以有不同数量的列(总是偶数),但总是以相同的方式拆分。我决定使用 Pandas,因为对于某些文件,输出将是 500,000 行,我认为它会加快速度。

输入:

h1  h2  h3  h4  h5  h6
A1  A2  A3  A4  A5  A6
B1  B2  B3  B4  B5  B6

预期输出

h1  h2  h3  h4  h5  h6
A1  A2
A1  A2  A3  A4
A1  A2  A3  A4  A5  A6
B1  B2
B1  B2  B3  B4
B1  B2  B3  B4  B5  B6

我尝试使用下面的代码(通过一些搜索和我自己的编辑拼凑在一起),你可以看到它很接近,但不是我需要的。

importFile = pd.read_csv('file.csv')
df = df_importFile = pd.DataFrame(importFile)

index_cols = ['h1']
cols = [c for c in df if c not in index_cols]

df2 = df.set_index(index_cols).stack().reset_index(level=1, drop=True).to_frame('Value')

df2 = pd.concat([pd.Series([v if i % len(cols) == n else ''
                        for i, v in enumerate(df2.Value)], name=col)
             for n, col in enumerate(cols)], axis=1).set_index(df2.index)


df2.to_csv('output.csv')

这给出了以下内容

h1  h2  h3  h4  h5  h6
A1  A2
A1      A3
A1          A4
A1              A5
A1                  A6

【问题讨论】:

    标签: python csv pandas dataframe


    【解决方案1】:
    # take number of columns and divide by 2
    # this is the number of pairs
    pairs = df.shape[1] // 2
    
    # np.repeat takes the number of rows and returns an object to slice
    # the dataframe array df.values... then slice... result should be 
    # of length pairs * len(df)
    a = df.values[np.repeat(np.arange(df.shape[0]), pairs)]
    
    # row values to condition with as column vector
    dim0 = (np.arange(a.shape[0]) % (pairs))[:, None ]
    
    # column values to condition with as row vector
    dim1 = np.repeat(np.arange(pairs), 2)
    
    # boolean mask to use in np.where generated
    # via the magic of numpy broadcasting
    mask = dim0 >= dim1
    
    # QED
    pd.DataFrame(np.where(mask, a, ''), columns=df.columns)
    

    【讨论】:

    • 这有效,但只命中前两行。它需要遍历输入文件中的每一行。
    • @mrh5028 未更新
    • 完美运行!现在努力了解到底发生了什么。
    • @mrh5028 添加了 cmets...为懒惰道歉。
    • 不需要,我自己试试。不过谢谢!这真的很有帮助!
    【解决方案2】:

    试试这个:

    dfNew = pd.DataFrame()
    ct = 1
    while ct <= df.shape[1]/2 :
        dfNew = dfNew.append(df[df.columns[:2*ct]])
        ct +=1
    
    dfNew.sort_values(['h1'], ascending=[True]).reset_index(drop=True).fillna("")
    print df
    
       h1  h2  h3  h4  h5  h6
    0  A1  A2                
    1  A1  A2  A3  A4        
    2  A1  A2  A3  A4  A5  A6
    3  B1  B2                
    4  B1  B2  B3  B4        
    5  B1  B2  B3  B4  B5  B6
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-26
      • 2020-04-19
      • 2020-02-19
      • 2020-02-23
      • 1970-01-01
      • 2018-08-14
      • 2023-02-16
      相关资源
      最近更新 更多