【问题标题】:add columns different length pandas添加列不同长度的熊猫
【发布时间】:2022-04-26 21:18:22
【问题描述】:

我在 Pandas 中添加列时遇到问题。 我有DataFrame,维度是nxk。在此过程中,我需要添加维度为 mx1 的列,其中 m = [1,n],但我不知道 m。

当我尝试这样做时:

df['Name column'] = data    
# type(data) = list

结果:

AssertionError: Length of values does not match length of index   

我可以添加不同长度的列吗?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    如果您使用接受的答案,您将丢失列名,如接受的答案示例中所示,并在documentation 中描述(强调添加):

    生成的轴将标记为 0, ..., n - 1。如果您要连接对象,而连接轴没有具有有意义的索引信息。

    看起来列名 ('Name column') 对原始海报/原始问题有意义。

    要保存列名,请使用pandas.concat,但不要 ignore_indexignore_index 的默认值为false;因此您可以完全省略该参数)。继续使用axis=1

    import pandas
    
    # Note these columns have 3 rows of values:
    original = pandas.DataFrame({
        'Age':[10, 12, 13], 
        'Gender':['M','F','F']
    })
    
    # Note this column has 4 rows of values:
    additional = pandas.DataFrame({
        'Name': ['Nate A', 'Jessie A', 'Daniel H', 'John D']
    })
    
    new = pandas.concat([original, additional], axis=1) 
    # Identical:
    # new = pandas.concat([original, additional], ignore_index=False, axis=1) 
    
    print(new.head())
    
    #          Age        Gender        Name
    #0          10             M      Nate A
    #1          12             F    Jessie A
    #2          13             F    Daniel H
    #3         NaN           NaN      John D
    

    请注意 John D 没有年龄或性别。

    【讨论】:

    • 这个答案是我的选择,也只是一个评论,如果你使用你的 Pandas 数据框,部分是用 pd.to_csv("filename") 写入 csv 这实际上(通过默认)用空白替换所有 NAN,留下一个干净的 csv 导入其他地方....
    【解决方案2】:

    使用 concat 并传递 axis=1ignore_index=True

    In [38]:
    
    import numpy as np
    df = pd.DataFrame({'a':np.arange(5)})
    df1 = pd.DataFrame({'b':np.arange(4)})
    print(df1)
    df
       b
    0  0
    1  1
    2  2
    3  3
    Out[38]:
       a
    0  0
    1  1
    2  2
    3  3
    4  4
    In [39]:
    
    pd.concat([df,df1], ignore_index=True, axis=1)
    Out[39]:
       0   1
    0  0   0
    1  1   1
    2  2   2
    3  3   3
    4  4 NaN
    

    【讨论】:

    • @TheRedPea 我回滚了您的编辑,您的建议应该是评论而不是对我的答案的编辑,因为编辑应该用于改进或更正答案,而不是建议替代答案跨度>
    • 肯定要下到“红豌豆”的答案,更准确。
    【解决方案3】:

    我们可以将不同大小的列表值添加到DataFrame中。

    例子

    a = [0,1,2,3]
    b = [0,1,2,3,4,5,6,7,8,9]
    c = [0,1]
    

    查找所有列表的长度

    la,lb,lc = len(a),len(b),len(c)
    # now find the max
    max_len = max(la,lb,lc)
    

    根据确定的最大长度调整全部大小(本例中没有

    if not max_len == la:
      a.extend(['']*(max_len-la))
    if not max_len == lb:
      b.extend(['']*(max_len-lb))
    if not max_len == lc:
      c.extend(['']*(max_len-lc))
    

    现在所有列表的长度相同并创建数据框

    pd.DataFrame({'A':a,'B':b,'C':c}) 
    

    最终输出是

       A  B  C
    0  1  0  1
    1  2  1   
    2  3  2   
    3     3   
    4     4   
    5     5   
    6     6   
    7     7   
    8     8   
    9     9  
    

    【讨论】:

      【解决方案4】:

      我遇到了同样的问题,两个不同的数据框并且没有一个共同的列。我只需要将它们放在一起放在一个 csv 文件中。

      • 合并: 在这种情况下,“合并”不起作用;甚至向两个 dfs 添加一个临时列,然后将其删除。因为这种方法使两个dfs具有相同的长度。因此,它重复较短数据帧的行以匹配较长数据帧的长度。
      • 连接: The Red Pea 的想法对我不起作用。它只是将较短的df附加到较长的df(按行),同时在较短的df列上方留下一个空列(NaN)。
      • 解决方案:您需要执行以下操作:
      df1 = df1.reset_index()
      df2 = df2.reset_index()
      df = [df1, df2]
      df_final = pd.concat(df, axis=1)
      
      df_final.to_csv(filename, index=False)
      

      这样,您将看到您的 dfs 彼此并排(按列),每个都有自己的长度。

      【讨论】:

        【解决方案5】:

        如果有人想替换不同大小的特定列而不是添加它。

        基于这个答案,我使用 dict 作为中间类型。 Create Pandas Dataframe with different sized columns

        如果要插入的列不是列表而是已经是字典,则可以省略相应的行。

        def fill_column(dataframe: pd.DataFrame, list: list, column: str):
            dict_from_list = dict(enumerate(list)) # create enumertable object from list and create dict
        
            dataFrame_asDict = dataframe.to_dict() # Get DataFrame as Dict
            dataFrame_asDict[column] = dict_from_list # Assign specific column
        
            return pd.DataFrame.from_dict(dataFrame_asDict, orient='index').T # Create new DataSheet from Dict and return it
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-11-19
          • 2023-02-07
          • 2015-05-02
          • 2021-08-15
          • 2018-04-28
          • 2019-09-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多