简体   繁体   English

熊猫为每一列选择不同的行

[英]Pandas select different rows for each column

I have a dataframe which consists of Date and three columns as below. 我有一个由日期和以下三列组成的数据框。

df = pd.DataFrame({'Date': ['01/01/2019', '02/01/2019', '03/01/2019', '04/01/2019', '05/01/2019', '06/01/2019', '07/01/2019', '08/01/2019'],
               'A': [1,2,3,4,5,6,7,8],
               'B': [11,12,13,14,15,16,17,18],
               'C': [21,22,23,24,25,26,27,28]})

I am trying to select parts of each column based on the date. 我试图根据日期选择每列的一部分。 If not selected looking to return zero. 如果未选择,则返回零。 As below. 如下。

df = pd.DataFrame({'Date': ['01/01/2019', '02/01/2019', '03/01/2019', '04/01/2019', '05/01/2019', '06/01/2019', '07/01/2019', '08/01/2019'],
               'A': [1,2,0,0,5,6,7,8],
               'B': [0,0,0,0,0,16,17,18],
               'C': [21,22,0,0,0,0,0,0]})

In the example So: 'A' would be sliced 01/01/2019 to 02/01/2019 and 05/01/2019 to 08/01/2019 (or no end slice). 在示例So中:将'A'切片为01/01/2019至02/01/2019和05/01/2019为08/01/2019(或无末尾切片)。 B would be sliced 06/01/2019 to 08/01/2019 (or no end slice as that is the last data pointy. C would be sliced 01/01/2019 to 02/01/2019. B将被切片为06/01/2019至08/01/2019(或没有结束切片,因为这是最后一个数据点.C将被切片为01/01/2019至02/01/2019。

From what I understood, you can try and use df.where() : 据我了解,您可以尝试使用df.where()

df['B']=df['B'].where(df.Date.between('06/01/2019','08/01/2019'),0)
print(df)

         Date  A   B   C
0  01/01/2019  1   0  21
1  02/01/2019  2   0  22
2  03/01/2019  3   0  23
3  04/01/2019  4   0  24
4  05/01/2019  5   0  25
5  06/01/2019  6  16  26
6  07/01/2019  7  17  27
7  08/01/2019  8  18  28

You can do same operations for all column and conditions you want. 您可以对所需的所有列和条件执行相同的操作。

I would generate a Boolean mask: 我会生成一个布尔掩码:

B_dates = df['Dates'][-3:]
df.loc[~df['Date'].isin(B_dates), 'B'] = 0

Of course you can iterate over this for any dates and columns you choose. 当然,您可以针对所选的任何日期和列对此进行迭代。

Here is the output of running this code on your df and printing it: 这是在df上运行此代码并打印的输出:

     Date      A   B   C
0  01/01/2019  1   0  21
1  02/01/2019  2   0  22
2  03/01/2019  3   0  23
3  04/01/2019  4   0  24
4  05/01/2019  5   0  25
5  06/01/2019  6  16  26
6  07/01/2019  7  17  27
7  08/01/2019  8  18  28

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM