将新行添加到现有数据框

时间:2017-11-26 19:22:38

标签: python pandas dataframe

我正在尝试将新记录插入数据框并收到此错误 - DataFrame constructor not Properly called

这是我的代码,

import pandas as pd

#defining the dataframe
dfHeader = { 'Name': [], 'Daily': [],'Weekly': [],'Monthly': [],'Yearly': [],
             'Area': [], 'Latitude':[] , 'Longitude':[] ,'Amenity': [] }

dFrame = pd.DataFrame(dfHeader)
print(dFrame)
Name = "NA"
DailyPrice = "NA"
WeeklyPrice = "NA"
MonthlyPrice = "NA"
YearlyPrice = "NA"
Area = "NA"
latitude = "NA"
longitude = "NA"
Amenity = "NA"

row = (Name, DailyPrice, WeeklyPrice, MonthlyPrice, YearlyPrice, Area, latitude, longitude, Amenity)

print(row)

dFrame = dFrame.append(pd.DataFrame(row))

请帮助我。

2 个答案:

答案 0 :(得分:1)

如果您需要添加一行:

In [136]: dFrame.loc[len(dFrame)] = row

In [137]: dFrame
Out[137]:
  Amenity Area Daily Latitude Longitude Monthly Name Weekly Yearly
0      NA   NA    NA       NA        NA      NA   NA     NA     NA

注意:通常它会更好,更快,更少内存消耗(这取决于......)先将数据收集到列表列表中,然后再调用pd.DataFrame()构造函数 /强>:

In [138]: data = [row, np.arange(9)]

In [139]: cols = 'Amenity Area Daily Latitude Longitude Monthly Name Weekly Yearly'.split()

In [140]: df = pd.DataFrame(data, columns=cols)

In [141]: df
Out[141]:
  Amenity Area Daily Latitude Longitude Monthly Name Weekly Yearly
0      NA   NA    NA       NA        NA      NA   NA     NA     NA
1       0    1     2        3         4       5    6      7      8

答案 1 :(得分:0)

您无法从元组创建DataFrame。但是,您可以从元组创建Series,并将标记设为dFrame的列:

dFrame.append(pd.Series(row, index=dfHeader.keys()), ignore_index=True)