【问题标题】:How to add new rows to a Pandas Data Frame with varying column numbers?如何将新行添加到具有不同列号的 Pandas 数据框中?
【发布时间】:2020-03-08 02:41:55
【问题描述】:

我想在 Pandas 数据框中添加新行,而不考虑每个新行中的顺序和列数。

当我添加新行时,我希望我的数据框如下所示。每行可以有不同的列数。

---- | 1    | 2    | 3    | 4 
row1 | data | data | 
row2 | data | data | data 
row3 | data | 
row4 | data | data | data | data 

【问题讨论】:

  • “我不重视列”? pandas dataframe 中的数据指的是列。如果您只想将数据存储在“行”中,请使用 dictionary 并将行标识符作为键,将元组或列表中的数据作为值。

标签: python pandas dataframe dataset


【解决方案1】:

在 pandas 中,您可以将新行与现有数据框连接起来(即使新行具有不同的列数),如下所示。

import pandas as pd

df = pd.DataFrame([list(range(5))])
new_row = pd.DataFrame([list(range(4))])
pd.concat([df,new_row], ignore_index=True, axis=0)

在上面的代码sn-p中,pd.concatenate函数合并了两个数据框。如果您提供参数 ignore_index=True,pandas 将合并两个数据帧而不考虑它们的长度。

【讨论】:

    【解决方案2】:

    大熊猫dataframe一行一次通常很慢。一个解决方案是首先在字典中收集数据,然后将其转换为DataFrame以进行进一步处理:

    d = {
        'att1': ['a', 'b'],
        'att2': ['c', 'd', 'e'],
        'att3': ['f'],
        'att4': ['g', 'h', 'i', 'j'],
    }
    df = pd.DataFrame.from_dict(d, orient='index')
    

    df包含:

            0    1    2    3
    att1    a    b    None None
    att2    c    d    e    None
    att3    f    None None None
    att4    g    h    i    j
    

    或更多符合典型的熊猫格式,将数据存储在一个长长的系列中,其中'att1'用作值'a'和'b'等的索引。:

    series = df.stack().reset_index(level=1, drop=True)
    

    允许轻松选择各种属性:

    series.loc[['att1', 'att3']]
    

    返回:

    att1    a
    att1    b
    att3    f
    

    【讨论】:

    • pandas是一个柱状数据结构;使用字典等可能会更好。否则+1 Swier; imho,你可以在这里存档最好的。 span>
    猜你喜欢
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 2022-12-10
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    相关资源
    最近更新 更多