简体   繁体   中英

create DataFrame from each row of another DataFrame in grouped columns?

Goal: Transforming each row of a DataFrame A into a new Dataframe B. This new Dataframe B should contain a group of columns from A in each row. If there are 6 groups, there should be 6 rows in each B.

Question: I managed to do the above, i was just wondering if there's a more pythonic way to doing that? I already tried to simplify as much as possible still i got the feeling there's an easier solution. Here's my approach:

import pandas as pd
import numpy as np

A = pd.DataFrame(np.random.rand(100,3), columns=['A_1','B_1','B_2'])
slices = [['A_1','A_2'],['B_1','B_2']]

def create_timeseries(data, slices):
    sliced_cols = [list(data.columns[data.columns.isin(i)]) for i in slices]
    len_slices = [0] + [len(sliced_cols[i]) for i in range(len(sliced_cols))]
    len_slices = np.cumsum(len_slices) 
    final_sliced_data = []
    for i, rows in enumerate(data.iterrows()):
        mat = np.zeros((len(sliced_cols), len_slices[-1]))
        for j, slices in enumerate(sliced_cols):
            mat[j, len_slices[j]:len_slices[j+1]] = rows[1].loc[slices]
        final_sliced_data.append(pd.DataFrame(mat, columns=sum(sliced_cols, [])))
    return final_sliced_data

B = create_timeseries(A, slices)

# have a look at first tranformed row
B[0]

Example:

Input (100 Observations):

A:
         A_1       B_1       B_2
0   0.574628  0.521426  0.161865
1   0.137718  0.237061  0.124890
2   0.753827  0.032432  0.785584
3   0.611985  0.606326  0.585408
4   0.676480  0.543213  0.055162
..       ...       ...       ...
95  0.383652  0.189211  0.223110
96  0.063715  0.312059  0.233206
97  0.886396  0.072423  0.108809
98  0.853179  0.314846  0.907006
99  0.302820  0.402470  0.152462

[100 rows x 3 columns]

Output (First 2 Observations):

B[0]:
        A_1       B_1       B_2
0  0.574628  0.000000  0.000000
1  0.000000  0.521426  0.161865

B[1]:
        A_1       B_1      B_2
0  0.137718  0.000000  0.00000
1  0.000000  0.237061  0.12489

Try this:

B = A.apply(lambda x: pd.DataFrame([[x.A_1,0,0],[0, x.B_1, x.B_2]], columns=A.columns), axis=1).tolist()

Alternative solution:

B = pd.DataFrame(data=np.repeat(A.values, 2, axis=0), columns=A.columns)
B.loc[1::2, 'A_1'] = 0
B.loc[::2 ,['B_1', 'B_2']] = 0
B = [B.iloc[i:i+2, :] for i in range(0, len(B), 2)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM