熊猫:一列中的True或False系列,当存在True时,在另一列中选择值

时间:2019-02-21 13:19:33

标签: python pandas

我的数据框如下:

 price          High_cross
 0.00224311     False
 0.00224473     False
 0.00224422     False
 0.00224697     True
 0.00224899     True
 0.00224668     True
 0.00224967     True
 0.00224967     True
 0.00224983     True
 0.00225143     False

我需要做的是在列High_cross上循环,当有True时,选择相关的price并将其与price进行比较,最后一个{系列的{1}}。如果第一个价格低于第二个价格,请在True的新列movement中进行通知。在此示例中,它应该看起来像这样:

True

(因为0.00224983大于0.00224697)!

我尝试使用索引,但相对而言卡住了...任何解决方案/想法?谢谢

2 个答案:

答案 0 :(得分:2)

考虑以下df:

var records = ((IEnumerable)enumerable).Cast<object>().ToList();
var result = new Dictionary<string, IList<string>>();
foreach (object record in records)
{
    foreach (var propertyName in properties)
    {
        var colValue = record.GetType().GetProperty(propertyName).GetValue(record, null);

        if (colValue != null)
        {
            if (result.ContainsKey(propertyName))
            {
                result[propertyName].Add(colValue.ToString());
            }
            else
            {
                result.Add(propertyName, new List<string>() { colValue.ToString() });
            }
        }
    }
}

使用:

       price  High_cross
0   0.002243       False
1   0.002245       False
2   0.002244       False
3   0.002247        True
4   0.002249        True
5   0.002247        True
6   0.002250        True
7   0.002250        True
8   0.002250        True
9   0.002251       False
10  0.002251        True
11  0.002250        True

答案 1 :(得分:0)

我不确定我是否完全了解您的目标是什么。我评估:

  1. 如果相应的High_Cross == True,请选择价格
  2. 将价格与High_Cross == True的最后价格进行比较
  3. 如果当前价格<上一个价格[High_Cross == True],则设置各自的运动= True

但是以下代码实现了我认为的目标:

import numpy as np
np.random.seed(5)
X = np.random.choice(range(10), size=10, replace=True).tolist()
Y = np.random.randint(2, size=10)
Y = [bool(y) for y in Y]

lst = []
movement = []
# Extract list of all true values
for price,cross in zip(X,Y):
    # Create list of tuples
    cross == True and lst.append((price,cross)) # If one liner avoiding the otherwise mandatory else statement

# Now do the work itself
for price,cross in zip(X,Y):
    movement.append(True) if cross == True and price > lst[-1][0] else movement.append(False)
    print("Price="+str(price)+", High_Cross="+str(cross)+", Movement="+str(movement[-1]))

产生:

Price=3, High_Cross=True, Movement=True
Price=6, High_Cross=False, Movement=False
Price=6, High_Cross=True, Movement=True
Price=0, High_Cross=True, Movement=False
Price=9, High_Cross=True, Movement=True
Price=8, High_Cross=True, Movement=True
Price=4, High_Cross=False, Movement=False
Price=7, High_Cross=True, Movement=True
Price=0, High_Cross=False, Movement=False
Price=0, High_Cross=True, Movement=False

`