python - 多个 for 循环来创建 pandas 数据框
问题描述
我正在尝试创建一个看起来像这样的熊猫数据框:
-5 0 5
index
-5 NaN slope slope
0 slope NaN slope
5 slope slope NaN
但我能得到的最接近的是下面的代码,它返回一个只有一列的数据帧(这是通过 ctr1 循环的最后一次迭代的列表)
weather = np.linspace(-5, 5, 3)
for ctr1 in weather:
slope_list = []
X1 = round(ctr1,1)
for ctr2 in weather:
X2 = round(ctr2,1)
Y1 = regressor[0] * X1**3 + \
regressor[1] * X1**2 + \
regressor[2] * X1 + \
regressor[3]
Y2 = regressor[0] * X2**3 + \
regressor[1] * X2**2 + \
regressor[2] * X2 + \
regressor[3]
slope = (Y2-Y1)/(X2-X1)
slope_list.append(slope)
df_final = pd.DataFrame({X1:slope_list})
任何人都可以帮忙吗?
解决方案
df_final 仅获得 3 个元素,因为它与 的缩进级别相同for ctr2 in weather
,因此每个外部循环都会重新分配它。虽然,如果你解决了这个问题,你会得到一个只有一个长列的数据框:你只有一个slope_list
附加到最后变成一个数据框的数据框。
这就是我在不改变分配方法的情况下解决这个问题的方法:
weather = np.linspace(-5, 5, 3)
slope_list = []
for ctr1 in weather:
X1 = round(ctr1,1)
for ctr2 in weather:
X2 = round(ctr2,1)
Y1 = regressor[0] * X1**3 + \
regressor[1] * X1**2 + \
regressor[2] * X1 + \
regressor[3]
Y2 = regressor[0] * X2**3 + \
regressor[1] * X2**2 + \
regressor[2] * X2 + \
regressor[3]
slope = (Y2-Y1)/(X2-X1)
slope_list.append(slope)
#make it 3 columns and 3 rows as intended
slope_list = np.array(slope_list).reshape(3, 3)
#make the dataframe
df_final = pd.DataFrame({X1:slope_list})
#manually add the desired row and column indexes
df_final = df.set_index(weather)
df_final.columns = weather
尽管您应该记住,除非您确切知道自己在做什么,否则在使用 pandas 时创建循环和嵌套循环通常意味着您错过了一种更简单、更好的处理方式。
推荐阅读
- jquery - Ruby On Rails - 访问 JQuery 中的 current_user 属性
- c++ - Visual Studio 19 C++ 命名空间问题(没有成员错误)
- python - 我无法启动 Jupyter Notebook
- node.js - 如何限制 NodeJS 中的页面访问?
- spring-integration - 在 Spring 集成 sftp 中的流处理期间休眠
- bash - 导出新的 $HOME 后需要使用我的 .ssh_config
- amazon-web-services - 设置 SSL 证书时无法从另一台服务器连接到 Redis
- c# - 创建 XML 文件时如何修改默认缩进值?
- python - 逻辑回归返回太多系数
- javascript - Ruby on Rails 使用 OR 查找