向空的 Pandas 数据框添加一行 [重复]

Posted

技术标签:

【中文标题】向空的 Pandas 数据框添加一行 [重复]【英文标题】:Adding a Row to an Empty Pandas Dataframe [duplicate] 【发布时间】:2020-10-13 22:35:52 【问题描述】:

我正在尝试解析我从网络上抓取的住房数据。对于每所房子,我将特征存储在一个列表中。我想将每个房子的特征(例如卧室、浴室、平方英尺等)放入同一 pandas 数据框中的一行。但是,当我尝试下面的代码时,我的数据框的标题出现了,但没有任何内容。我在这里错过了什么?

def processData(url):
    
    #Rest of function omitted as it is not relevant to the question at hand.
    
    entry = [location, price, beds, baths, sqft, lotSize, neighborhoodMed, dom, built, hs, 
          garage, neighborhood, hType, basementSize]

    df = pd.DataFrame(columns = ["Address", "Price", "Beds", "Baths", "SqFt", "LotSize", 
                                 "NeighborhoodMedian", "DOM", "Built", "HighSchool", "Garage", 
                                "Neighborhood", "Type", "BasementSize"])

    df.append(entry) #This line doesn't work
    
    return df

输出:

【问题讨论】:

您需要重新分配df=df.append(entry) @ScottBoston 谢谢你的帮助,但现在我的内容是垂直的而不是水平的。 试试看,df.append(dict(zip(df.columns, entry)), ignore_index=True) 【参考方案1】:

只是猜测您的要求,但请尝试以下操作

import pandas as pd

location, price, beds, baths, sqft, lotSize, neighborhoodMed, dom, built, hs, garage, neighborhood, hType, basementSize = range(
    14)
entry = [
    location, price, beds, baths, sqft, lotSize, neighborhoodMed, dom, built,
    hs, garage, neighborhood, hType, basementSize
]

columns = [
    "Address", "Price", "Beds", "Baths", "SqFt", "LotSize",
    "NeighborhoodMedian", "DOM", "Built", "HighSchool", "Garage",
    "Neighborhood", "Type", "BasementSize"
]

df = pd.DataFrame(columns=columns)

df = df.append(
    dict(zip(columns, entry)), ignore_index=True)  #This line doesn't work

print(df)

【讨论】:

以上是关于向空的 Pandas 数据框添加一行 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

R:向空数据框添加行时丢失列名

jquery 向空数组中添加元素,重复的就不添加到空数组中请问该如何编写

熊猫将空的对象列添加到数据框[重复]

加快pandas DataFrame中每一行的发布请求[重复]

Pandas:如何将具有重复索引值的数据框转换为字典

无重复的 Pandas 外连接添加新行