![](/img/trans.png)
[英]Fill NaNs of pandas.DataFrame based on condition over another column
[英]pandas: fill nans given a condition
我正在努力处理一些看似微不足道的事情,但显然并非如此。 常规图片: data
-熊猫数据TOTAL_VISITS
-包含(以及其他) TOTAL_VISITS
和NUM_PRINTS
列。
目标:给定num_prints
参数,找到NUM_prints = num_prints
行,并用给定的数字填充nan
。
我停下来的地方不再有意义了:
indices= data['NUM_PRINTS'] == num_prints
data.loc[indices,'TOTAL_VISITS'].fillna(5,inplace=True)
就我所知和阅读的内容而言,这应该起作用。 实际上没有在nans上填充任何东西,似乎它可以处理副本或其他东西,因为它不会更改原始对象中的任何东西。
什么有效:
data.loc[indices,'TOTAL_VISITS'] = 2
这确实会在num_print
条件下用2填充该列,但不考虑nans。
data['TOTAL_VISITS'].fillna(0, inplace=True)
这确实使总访问次数中的num_prints
填充为0,但不考虑num_prints
条件。
我有点绝望,因为带有.iloc
的常规for
循环和条件花的时间太长了,我无法处理。
我认为双方都需要过滤器,并且仅对过滤的行应用fillna
:
np.random.seed(1213)
c = ['TOTAL_VISITS', 'A', 'NUM_PRINTS']
data = pd.DataFrame(np.random.choice([1,np.nan,3,4], size=(10,3)), columns=c)
print (data)
TOTAL_VISITS A NUM_PRINTS
0 1.0 4.0 4.0
1 NaN 3.0 1.0
2 1.0 1.0 1.0
3 4.0 3.0 3.0
4 1.0 3.0 4.0
5 4.0 4.0 3.0
6 4.0 1.0 4.0
7 NaN 4.0 3.0
8 NaN NaN 3.0
9 3.0 NaN 1.0
num_prints = 1
indices= data['NUM_PRINTS'] == num_prints
data.loc[indices,'TOTAL_VISITS'] = data.loc[indices,'TOTAL_VISITS'].fillna(100)
#alternative
#data.loc[indices,'TOTAL_VISITS'] = data['TOTAL_VISITS'].fillna(100)
print (data)
TOTAL_VISITS A NUM_PRINTS
0 1.0 4.0 4.0
1 100.0 3.0 1.0
2 1.0 1.0 1.0
3 4.0 3.0 3.0
4 1.0 3.0 4.0
5 4.0 4.0 3.0
6 4.0 1.0 4.0
7 NaN 4.0 3.0
8 NaN NaN 3.0
9 3.0 NaN 1.0
我认为这很好
data['TOTAL_VISITS'] = np.where(data['NUM_PRINTS'] == 1, 100, data['TOTAL_VISITS'])
不使用fillna
来应用逻辑的一种方法是定义一个包含您的条件的掩码。 然后使用此掩码通过.loc
更新系列。
以下示例适用于@jezrael中的数据。
num_prints = 1
mask = (data['NUM_PRINTS'] == num_prints) & data['TOTAL_VISITS'].isnull()
data.loc[mask, 'TOTAL_VISITS'] = 100
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.