python-3.x - 如何在特定列中找到特定值的行索引,然后以该起点创建新列?
问题描述
我想用我的数据框做什么......
- 找到特定列中的第一个 0 值(示例照片中的 G)。
- 创建一个值 0 的新列 (Time),与列 (G) 中的相同 0 值对齐。
- 然后每一行在列 (Time) +(1/60) 中的 0 之后直到数据结束。
- 和 -(1/60) 在 (Time) 列中的 0 之前直到数据的开头。
实现这一目标的最佳方法是什么?任何意见,将不胜感激。谢谢你。
解决方案
非常直截了当
- 识别包含您要查找的值的行的索引
- 然后构造一个数组,其中 start 为负数,零将是索引行并以系列结尾的值结束
import numpy as np
df = pd.DataFrame({"Time":np.full(25, 0), "G":[i if i>0 else 0 for i in range(10,-15,-1)]})
# find the where value is zero
idx = df[df["G"]==0].index[0]
intv = round(1/60, 3)
# construct a numpy array from a range of values (start, stop, increment)
df["Time"] = np.arange(-idx*intv, (len(df)-idx)*intv, intv)
df.loc[idx, "Time"] = 0 # just remove any rounding at zero point
print(df.to_string(index=False))
输出
Time G
-0.170 10
-0.153 9
-0.136 8
-0.119 7
-0.102 6
-0.085 5
-0.068 4
-0.051 3
-0.034 2
-0.017 1
0.000 0
0.017 0
0.034 0
0.051 0
0.068 0
0.085 0
0.102 0
0.119 0
0.136 0
0.153 0
0.170 0
0.187 0
0.204 0
0.221 0
0.238 0
推荐阅读
- python - sklearn 'preprocessor' 子模块在导入时不可用
- javascript - 发球断纱
- c - Pthreads,如何防止倒计时锁存器中的死锁
- elixir - 如何通过 |> 长生不老药中的运算符传递附加参数
- node.js - 在按每个用户 ID 映射和获取用户详细信息时,API 未正确获取用户的数据
- c# - Unity中的线程以避免动画冻结
- php - 如何使用 php 更新 MongoDB 数据库中的集合?
- javascript - Minecraft 服务器客户端通过 Discord Bot
- swift - 当字节长于 20 时如何修复此代码?
- javascript - 在对象原型中使用 arguments.length