python - 将相同的值添加到多组行。值根据条件变化
问题描述
我有一个动态创建的数据框。我将我的第一组行创建为:
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'
我怎样才能做到这一点?
解决方案
使用字典将行添加到您的数据框中,这是一种更快的方法。这是一个例如
第 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)
参考:
推荐阅读
- linux - 我可以在 shell 脚本的第一行省略“shebang”的完整路径吗?
- python - 关于 sum 函数的 Python 弃用警告
- python - ValueError:超出最大允许尺寸,AgglomerativeClustering fit_predict
- amazon-web-services - AWS Cloudformation 错误:由于递归导入而导致递归锁定
- wordpress - Elementor 插件无法在 localhost 上运行
- python - 消息未显示在管理 django 面板中
- symfony - 实体如何被持久化两次?
- django - Django 无法从 DetailView 更新另一个模型
- sql-server - 如何在 SQL Server 中对多列数据进行排名?
- ios - 如何在 Info.plist 中添加变量值