在Pandas数据框中将条件应用于它旁边的相同行和行

时间:2017-08-27 22:37:51

标签: python-2.7 pandas

我有我的pandas Data我想在行中检查条件并为第i行和第(i + 1)行分配值,这可能是最简单的方法。

using System;
using System.Text;
using System.Threading;

public class Test {

 private static long secret = 0xdeadbeef;
 private static int digits = 6;
 private static int period_size_in_seconds = 1;

 public string phonenumber;
 public int validperiods;

 private string reference(long delta) {
  // get current minute (UTC)
  long now = DateTime.Now.ToUniversalTime().ToFileTimeUtc();
  now /= (period_size_in_seconds * 10000000);
  // factor in phone number
  var inputBytes = Encoding.ASCII.GetBytes(phonenumber);
  long mux = 0;
  foreach(byte elem in inputBytes) {
    mux ^= elem;
    mux <<= 1;
   }
   // limit number of digits
  long mod = Convert.ToInt64(Math.Pow(10, digits)) - 1; // how many digits?
  // apply time shift for validations
  now -= delta;
  // and play a little bit
  now *= mux; // factor in phone number
  now ^= secret; // play a bit
  now >>= 1; // with the number
  if (0 != (now & 0x1)) { // to make the code 
   now >>= 1; // read about LFSR to learn more
   now ^= secret; // less deterministic
  }
  now = Math.Abs(now);
  now %= mod; // keep the output in range
  return now.ToString().PadLeft(digits, '0');
 }

 public string getTimeVariable() {
  return reference(0);
 }

 public bool verifyVariable(string variable) {
  for (int i = 0; i < validperiods; i++) {
   if (variable == reference(i)) {
    return true;
   }
  }
  return false;
 }

 public void test() {
  phonenumber = "+48602171819";
  validperiods = 900;
  string code = getTimeVariable();

  if (verifyVariable(getTimeVariable()))
   System.Console.Write("OK1");

  if (verifyVariable(code))
   System.Console.Write(" OK2");

  Thread.Sleep(2*1000*period_size_in_seconds);

  if (verifyVariable(code)) {
   System.Console.WriteLine(" OK3");
  }

  System.Console.WriteLine(code);
 }

 public static void Main() {
  (new Test()).test();
 }
}

我试过这样的话:

x=pd.DataFrame(np.random.rand(10))

如果值小于0.5并且分配'Y',我想检查每一行,但如果在第一行中已经指定'Y',则连续行也应该具有'Y'否则'N' ”。

结果应如下所示

status=np.where(x<0.5,'Y','N')

1 个答案:

答案 0 :(得分:3)

df.assign(status=np.where((x<0.5) | (x.shift(1)<0.5),'Y','N'))

输出:

            status
0  0.652753      N
1  0.756219      N
2  0.299177      Y
3  0.851635      Y
4  0.942549      N
5  0.686693      N
6  0.071128      Y
7  0.482733      Y
8  0.979321      Y
9  0.830639      N