我有一个动态创建的数据框。 我将第一组行创建为:
df['tourist_spots'] = pd.Series(<A list of tourist spots in a city>)
我在此df中添加:
df['city'] = <City Name>
到目前为止,一切都很好。为多个旅游景点创建了具有相同城市名称的一排行。
我想添加一个新城市。所以我这样做:
df['tourist_spots'].append(pd.Series(<new data>))
现在,当我在新城市中附加以下内容:
df['city'].append('new city')
以前更新的城市数据不见了。就像每次替换行而不追加行一样。
这是我想要的例子:
步骤1:
df['tourist_spot'] = pd.Series('Golden State Bridge' + a bunch of other spots)
对于我想要的上述数据创建的所有行:
df['city'] = 'San Francisco'
第2步:
df['tourist_spot'].append(pd.Series('Times Square' + a bunch of other spots)
对于上述数据创建的所有行,我想要:
df['city'] = 'New York'
我该如何实现?
答案 0 :(得分:1)
使用字典将行添加到数据框中,这是一种更快的方法。 这是例如
STEP 1 创建字典:
dict_df = [{'tourist_spots': 'Jones LLC', 'City': 'Boston'},
{'tourist_spots': 'Alpha Co', 'City': 'Boston'},
{'tourist_spots': 'Blue Inc', 'City': 'Singapore' }]
STEP2 将字典转换为数据框:
df = pd.DataFrame(dict_df)
STEP3 以字典格式将新条目添加到数据框:
df = df.append({'tourist_spots': 'New_Blue', 'City': 'Singapore'}, ignore_index=True)
参考: