简体   繁体   English

当通过复杂索引和基于布尔的条件子集时,如何为熊猫数据框分配值?

[英]How to assign value to a pandas dataframe, when subset by complex index and boolean based conditions?

I would like to replace values in a pandas dataframe, with a complex subsetting pattern. 我想用复杂的子集模式替换熊猫数据框中的值。

With the .loc accessor, I was only able to subset by chaining multiple conditions, because some of the conditions are index based. 使用.loc访问器,我只能通过链接多个条件来进行子集化,因为某些条件是基于索引的。 But it seems I can not assign values after such a chain of subsetting. 但是似乎在这样的子集链之后我无法分配值。 UPDATE: A further problem is caused by the duplicated indicies. 更新:另一个问题是由重复的索引引起的。 I have updated the example accordingly. 我已经相应地更新了示例。

import numpy as np
import pandas as pd

df = pd.DataFrame({'a': ['foo'] * 10 + ['bar'] * 10, 'b': range(20)}, index=pd.date_range('2019-01-01','2019-01-10').append(pd.date_range('2019-01-01','2019-01-10')))

df.loc[df['a'] == 'foo', 'b'].loc[pd.to_datetime(['2019-01-05','2019-01-09'])] = np.nan

df

Result: 结果:

              a     b
2019-01-01  foo     0
2019-01-02  foo     1
2019-01-03  foo     2
2019-01-04  foo     3
2019-01-05  foo     4
2019-01-06  foo     5
2019-01-07  foo     6
2019-01-08  foo     7
2019-01-09  foo     8
2019-01-10  foo     9
2019-01-01  bar     10
2019-01-02  bar     11
2019-01-03  bar     12
2019-01-04  bar     13
2019-01-05  bar     14
2019-01-06  bar     15
2019-01-07  bar     16
2019-01-08  bar     17
2019-01-09  bar     18
2019-01-10  bar     19

Expected: 预期:

              a     b
2019-01-01  foo     0
2019-01-02  foo     1
2019-01-03  foo     2
2019-01-04  foo     3
2019-01-05  foo     NaN
2019-01-06  foo     5
2019-01-07  foo     6
2019-01-08  foo     7
2019-01-09  foo     NaN
2019-01-10  foo     9
2019-01-01  bar     10
2019-01-02  bar     11
2019-01-03  bar     12
2019-01-04  bar     13
2019-01-05  bar     14
2019-01-06  bar     15
2019-01-07  bar     16
2019-01-08  bar     17
2019-01-09  bar     18
2019-01-10  bar     19

I have tried alternative approaches like: 我尝试了其他方法,例如:

df.loc[df['a'] == 'foo' and df.index.isin(['2019-01-05','2019-01-09']), 'b']

which drops: 下降:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Not even this works, as the isin returns an array without the date based indexing: 甚至都不行,因为isin返回一个没有基于日期的索引的数组:

df['a'] == 'foo' and pd.Series(df.index.isin(['2019-01-05','2019-01-09']))

您可以使用loc分配的一个.loc链来做将是不安全的

df.loc[df.index.isin(['2019-01-05','2019-01-09'])&df.a.eq('foo'),'b']=np.nan

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

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