Skip to main content
 首页 » 编程设计

python之无法对 Pandas 数据框进行子集化

2024年10月17日7zhengyun_ustc

我在名为 in_file 的数据框中有以下数据:

Client  Value_01   Value_02   Date 
ABC     100       500       2016-09-01T 
ABC     14        90        2016-09-02T 
DEF     95        1000      2016-09-01T 
DEF     200       600       2016-09-02T 
GHI     75        19        2016-09-01T 
GHI     300       700       2016-09-02T 
JKL     50        02        2016-09-01T 
JKL     400       800       2016-09-02T 

我使用以下内容对数据框进行子集化(我们称之为“子集 1”):

df_01 = in_file.loc[(in_file.Date == '2016-09-01T') & (in_file.Client <> 'ABC') & (in_file.Client <> 'DEF')].sort_values('Value_01', ascending=False) 

然后我回来了:

Client  Value_01   Value_02   Date 
GHI     75        19        2016-09-01T 
JKL     50        02        2016-09-01T 

然后,我尝试使用以下内容对数据框进行子集化(我们称之为“子集 2”):

df_02 = in_file.loc[(in_file.Date == '2016-09-01T') & (in_file.Client == 'ABC') & (in_file.Client == 'DEF')].sort_values('Value_01', ascending=False) 

通过“子集 2”,我得到了一个空数据框。但是,我期待看到以下内容:

Client  Value_01   Value_02   Date 
ABC     100       500       2016-09-01T 
DEF     95        1000      2016-09-01T 

有谁知道为什么“子集 2”代码没有返回我期望的数据帧?

提前致谢。

请您参考如下方法:

包括isin():

In [28]: in_file.loc[(in_file.Date == '2016-09-01T') & in_file.Client.isin(['ABC', 'DEF'])].sort_values('Value_01', ascending=False) 
Out[28]: 
  Client  Value_01  Value_02         Date 
0    ABC       100       500  2016-09-01T 
2    DEF        95      1000  2016-09-01T 

不包括:

In [29]: in_file.loc[(in_file.Date == '2016-09-01T') & (~in_file.Client.isin(['ABC', 'DEF']))].sort_values('Value_01', ascending=False) 
Out[29]: 
  Client  Value_01  Value_02         Date 
4    GHI        75        19  2016-09-01T 
6    JKL        50         2  2016-09-01T 

或者慢一点,但是更好的 query() 方法:

In [30]: in_file.query("Date == '2016-09-01T' and Client in ['ABC', 'DEF']") 
Out[30]: 
  Client  Value_01  Value_02         Date 
0    ABC       100       500  2016-09-01T 
2    DEF        95      1000  2016-09-01T 
 
In [31]: in_file.query("Date == '2016-09-01T' and Client not in ['ABC', 'DEF']") 
Out[31]: 
  Client  Value_01  Value_02         Date 
4    GHI        75        19  2016-09-01T 
6    JKL        50         2  2016-09-01T