首页 > 解决方案 > 如何在特定列中找到特定值的行索引,然后以该起点创建新列?

问题描述

数据框示例

我想用我的数据框做什么......

实现这一目标的最佳方法是什么?任何意见,将不胜感激。谢谢你。

标签: python-3.xpandasdataframe

解决方案


非常直截了当

  1. 识别包含您要查找的值的行的索引
  2. 然后构造一个数组,其中 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

推荐阅读