首页 > 解决方案 > 将用户定义的行添加到数据集

问题描述

所以我和我的团队正在研究我们与里斯本住房市场命名为“lhm”的数据集。我们正在尝试构建一个工具,允许人们使用 add_sales_house 函数上传他们想要出售的房子。一些变量,如国家,是预定义的,其他变量将由用户选择。在将新房子(sellinghouse)添加为 lhm 数据集的新行之前,一切似乎都运行良好,因为我们之前正在使用该数据集。有谁知道如何解决这个问题?先感谢您

标签: pythonpandasdataset

解决方案


不是很清楚你在找什么,但这里有一个函数,它接受一个数据框和各种参数来返回一个新的数据框,并将传递的参数附加在一行中。

如果您有这样的数据框:

lhm = pd.DataFrame([["Blue House", "Portugal", 400000], ["White House", "Portugal", 200000]], columns = ["Name", "Country", "Price"])
lhm

Output:
          Name   Country   Price
0   Blue House  Portugal  400000
1  White House  Portugal  200000

您可以轻松定义一个函数,该函数采用与数据框中的列相关的特定参数。例如:

def add_selling_house(data, name, price, country = "Portugal", **kwargs):
  # Define your other arguments for this function

  # Use provided args to create a series. 
  # Ensure order matches however you defined it in the dataframe
  s = pd.Series([name,country, price], index = data.columns)

  # Append series to passed dataframe and return
  return data.append(s, ignore_index = True)

add_selling_house(lhm, "New House", 10000, "Spain")

Output:
          Name   Country   Price
0   Blue House  Portugal  400000
1  White House  Portugal  200000
2    New House     Spain   10000


推荐阅读