python - Pandas - 使用 range(x) 在“for”循环中填充数据框
问题描述
我有一个构建空数据框的函数,如下所示:
def malthusian_growth():
# formula
def growth1(r, x):
y = r*(1-x)
return y
todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')
columns = ["year", "population"]
df = pd.DataFrame(index=index, columns=columns)
现在我想用以下循环填充它:
population = 0.02
for item in range(10):
next_population = growth1(r=2.7, x=population)
population+=next_population
我该怎么做呢?
解决方案
您可以创建助手列表:
def growth1(r, x):
y = r*(1-x)
return y
out = []
population = 0.02
for item in range(10):
next_population = growth1(r=2.7, x=population)
population+=next_population
out.append(population)
todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')
columns = ["year", "population"]
df = pd.DataFrame({'population':out}, index=index)
print (df)
population
2020-04-10 2.666000
2020-04-11 -1.832200
2020-04-12 5.814740
2020-04-13 -7.185058
2020-04-14 14.914599
2020-04-15 -22.654818
2020-04-16 41.213190
2020-04-17 -67.362423
2020-04-18 117.216119
2020-04-19 -196.567402
推荐阅读
- php - 读取动态添加的复选框值
- dialogflow-es - 如何在单个 app.intent 函数中提及多个 Intent 调用
- python - 为什么我可以通过shell连接到MySQL,但不能通过Python连接?
- apache-kafka - 为多个 Kafka 主题重用一个模式
- path - 在rviz中绘制多条路径
- node.js - 在移动设备中打开 webapp 时不会触发 SocketIO 事件
- azure - 1 个应用程序的 2 个不同 Azure AD 域
- c# - Utf8JsonReader 阻塞 UI
- java - 尝试保存到数据库时使用 Spring Boot JPA 的 NullPointerException
- reactjs - 是否可以在 React 中使用 brotli 压缩?