【问题标题】:How to change one column of data to multiple column based on row using Python Pandas?如何使用 Python Pandas 根据行将一列数据更改为多列?
【发布时间】:2020-12-02 10:09:58
【问题描述】:

我不知道我是否正确地提出了问题.. 比如我想要

1
0
1
0
1
0
1
0

改成

1  0  1  
0  1  0
1  0  x

第一个列表不应更改.. 并将类型更改为 DataFrame..

我尝试使用 numpy.array,将数组展平。并使用 reshape(-1,3).T .. 但由于它有一些缺失值..我无法正确重塑数组..

【问题讨论】:

    标签: python-3.x numpy dataframe


    【解决方案1】:

    一种可能的解决方案是在调整大小之前将缺失值添加到数组中。

    起点:

    import numpy as np
    import pandas as pd
    
    # I assume you flattened the array.
    data = np.array([1, 0, 1, 0, 1, 0, 1, 0, ])
    

    根据所需的形状和填充值添加新数据:

    new_shape = (3, 3)
    fill_value = np.NaN
    
    missing_length = np.product(new_shape) - data.size
    missing_array = np.full(missing_length, fill_value)
    
    data = np.hstack([data, missing_array])
    

    然后应用重塑并将其转换为数据框:

    data = data.reshape(new_shape)
    
    df = pd.DataFrame(data)
    print(df)
    

    输出:

         0    1    2
    0  1.0  0.0  1.0
    1  0.0  1.0  0.0
    2  1.0  0.0  NaN
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      相关资源
      最近更新 更多