【问题标题】:How to add value to specific index that is out of bounds如何为超出范围的特定索引添加值
【发布时间】:2022-10-14 22:34:37
【问题描述】:

我有一个列表数组

列表 = [[0, 1, 2, 3, 4, 5],[0],[1],[2],[3],[4],[5]]

假设我将 [6, 7, 8] 添加到第一行作为我的三个新列的标题,那么在这些新列中添加值而不使索引超出范围的最佳方法是什么?我尝试先用“”填充所有三列,但是当我添加一个值时,它会将“”推到右侧并增加我的列表大小。

使用 Pandas 数据框会更容易吗?您是否允许在 Pandas 数据框中出现“间隙”?

【问题讨论】:

    标签: python-3.x pandas dataframe


    【解决方案1】:

    根据 ops 评论,我认为 pandas df 是更合适的解决方案。你不能有“差距”,但是像这样的 nan 值

    import pandas as pd
    
    # create sample data
    a = np.arange(1, 6)
    df = pd.DataFrame(zip(*[a]*5))
    
    print(df)
    

    输出:

       0  1  2  3  4
    0  1  1  1  1  1
    1  2  2  2  2  2
    2  3  3  3  3  3
    3  4  4  4  4  4
    4  5  5  5  5  5
    

    用于添加空列:

    # add new columns, not empty but filled w/ nan
    df[5] = df[6] = df[7] = float('nan')
    
    # fill single value in column 7, index 3
    df[7].iloc[4] = 123
    
    print(df)
    

    输出:

       0  1  2  3  4   5   6      7
    0  1  1  1  1  1 NaN NaN    NaN
    1  2  2  2  2  2 NaN NaN    NaN
    2  3  3  3  3  3 NaN NaN    NaN
    3  4  4  4  4  4 NaN NaN    NaN
    4  5  5  5  5  5 NaN NaN  123.0
    

    【讨论】:

    • 谢谢,但是如何在不填写索引 0-7 的情况下为第 3 行索引 8 添加值?
    • 你必须用占位符填充这些列,例如南但我认为熊猫解决方案更容易。查看编辑后的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 2019-02-19
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    相关资源
    最近更新 更多