python - 从分组列中另一个 DataFrame 的每一行创建 DataFrame?

标签 python pandas dataframe time-series slice

目标:将 DataFrame A 的每一行转换为一个新的 Dataframe B。这个新的 Dataframe B 应该在每一行中包含一组来自 A 的列。如果有6组,每个B应该有6行。

问题:我设法做到了上述,我只是想知道是否有更 pythonic 的方法来做到这一点?我已经尝试尽可能地简化,但我仍然觉得有一个更简单的解决方案。这是我的方法:

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]

示例:

输入(100 个观察):

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]

输出(前 2 个观察):

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

最佳答案

试试这个:

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()

关于python - 从分组列中另一个 DataFrame 的每一行创建 DataFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58380613/

相关文章:

python - 如何在 Python 中分割触摸字符?

python - 将 DTM 转换为文本

python - 如何使用 MultiIndex 索引和 MultiIndex 列对 Pandas DataFrame 进行切片?

python - 使用 pandas apply with dates and dates shifted

python - 在模板上显示表单

python - 限制 mysql 查询中的 str 字符

python - 如何优雅地忽略 Python 函数的某些返回值?

python - Pandas 在 Groupby 中重新索引日期

python - 具有固定效果的 Pandas

r - 从 data.frame 中的现有变量创建几个新的派生变量