【问题标题】:Adding a Row to an Empty Pandas Dataframe [duplicate]向空的 Pandas 数据框添加一行 [重复]
【发布时间】: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)

标签: python python-3.x pandas dataframe append


【解决方案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)

【讨论】:

    猜你喜欢
    • 2014-05-04
    • 1970-01-01
    • 2016-12-19
    • 2018-05-01
    • 2015-06-29
    • 1970-01-01
    • 2019-03-26
    • 2017-11-16
    • 1970-01-01
    相关资源
    最近更新 更多