python中index选所有的行_使用Datetimeindex选择行

好吧,所以有时候我喜欢把pandas数据帧看作字典。这是因为使用字典是如此的简单,把它们当作简单的字典来思考,通常意味着你可以找到解决问题的方法,而无需深入了解熊猫。在

所以在你的例子中,如果数据帧的值通过了一些值测试,我会创建一个公共日期列表,然后使用这些日期创建一个新的数据帧来访问现有数据帧中的值。在我的例子中,测试的是DF1中的值1+DF2中的value2是否大于10:import pandas as pd

import random

random.seed(123)

#Create some data

DF1 = pd.DataFrame({'Date' : ['1990-03-17', '1990-03-18', '1990-03-19',

'1990-03-20', '1990-03-21', '1990-03-22',

'1990-03-23', '1990-03-24', '1990-03-25',

'1990-03-26', '1990-03-27', '1990-03-28',

'1990-03-29', '1990-03-30', '1990-03-31',

'1990-04-01', '1990-04-02', '1990-04-03'],

'Value1' : [round(random.uniform(1, 10), 2)

for x in xrange(18)],

'Value2' : [round(random.uniform(1, 10), 2)

for x in xrange(18)]

})

DF2 = pd.DataFrame({'Date' : ['1990-03-25', '1990-03-26', '1990-03-27',

'1990-03-28', '1990-03-29', '1990-03-30',

'1990-03-31', '1990-04-01', '1990-04-02',

'1990-04-03'],

'Value1' : [round(random.uniform(1, 10), 2)

for x in xrange(10)],

'Value2' : [round(random.uniform(1, 10), 2)

for x in xrange(10)]

})

DF1.set_index('Date', inplace = True)

DF2.set_index('Date', inplace = True)

#Create a list of common dates, where the values of DF1.Value1 summed

#with DF.Value2 is greater than 10

Common_Set = list(DF1.index.intersection(DF2.index))

Common_Dates = [date for date in Common_Set if

DF1.Value1[date] + DF2.Value1[date] > 10]

#And now create the data frame I think you want using the Common_Dates

DF_Output = pd.DataFrame({'L_Value1' : [DF1.Value1[date] for date in Common_Dates],

'L_Value2' : [DF1.Value2[date] for date in Common_Dates],

'S_Value1' : [DF2.Value1[date] for date in Common_Dates],

'S_Value2' : [DF2.Value2[date] for date in Common_Dates]

}, index = Common_Dates)

正如评论建议的那样,这在熊猫身上肯定是可以做到的,但对我来说,这是一个简单的解决办法。常见的约会操作可以很容易地在一行中完成,但我没有为清楚起见。在

当然,如果两个数据帧中都有很多列,那么编写DF_Output DataFrame构造函数可能会非常痛苦。如果是这样的话,你可以这样做:

^{pr2}$

这两种方法都给了我:LValue1 LValue2 SValue1 SValue2

1990-03-25 8.67 6.16 3.84 4.37

1990-03-27 4.03 8.54 7.92 7.79

1990-03-29 3.21 4.09 7.16 8.38

1990-03-31 4.93 2.86 7.00 6.92

1990-04-01 1.79 6.48 9.01 2.53

1990-04-02 6.38 5.74 5.38 4.03

我想这不会让很多人满意,但这是我解决问题的方法。p、 如果你能在后面的问题中再做一些关于数据帧的工作,那就太好了。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值