首页 > 解决方案 > 将相同的值添加到多组行。值根据条件变化

问题描述

我有一个动态创建的数据框。我将我的第一组行创建为:

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'

我怎样才能做到这一点?

标签: pythonpython-3.xpandasdataframe

解决方案


使用字典将行添加到您的数据框中,这是一种更快的方法。这是一个例如

第 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)

参考:

  1. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html

推荐阅读