以下代码将给定的 pandas 列 FEAT
转换为名为 STREAM
的新二进制功能。只要原始数据帧中没有 NaN 值,该程序就可以工作。如果是这种情况,则会出现以下异常:ValueError:值的长度与索引的长度不匹配
。
我需要将 NaN 值推送到新列。可行吗?
这是失败的代码选项:
import pandas as pd
import numpy as np
data = {
'FEAT': [8, 15, 7, np.nan, 5, 2, 11, 15]
}
customer = pd.DataFrame(data)
customer = pd.DataFrame(data, index=['June', 'Robert', 'Lily', 'David', 'Bob', 'Sally', 'Mia', 'Luis'])
#create binary variable STREAM 0:mainstream 1:avantgarde
stream_0 = [1, 3, 5, 8, 10, 12, 14]
stream_1 = [2, 4, 6, 7, 9, 11, 13, 15]
# convert FEAT to list_0
list_0 = customer['FEAT'].values.tolist()
# create a list of length = len(customer) whose elements are:
# 0 if the value of 'FEAT' is in stream_0
# 1 if the value of 'FEAT' is in stream_1
L = []
for i in list_0:
if i in stream_0:
L.append(0)
elif i in stream_1:
L.append(1)
# convert the list to a new column of customer df
customer['STREAM'] = L
print(customer)
最佳答案
问题是您缺少 else
当一个值(如 NaN
)不在 stream_0
中时阻止 so也不stream_1
您不执行任何操作,这会导致 L 的元素少于 customer
中的行数.
这里不需要循环,np.select
可以处理列的创建。 default
参数将处理 else
堵塞。
customer['STREAM'] = np.select([customer.FEAT.isin(stream_0), customer.FEAT.isin(stream_1)],
[0, 1], default=np.NaN)
FEAT STREAM
June 8.0 0.0
Robert 15.0 1.0
Lily 7.0 1.0
David NaN NaN
Bob 5.0 0.0
Sally 2.0 1.0
Mia 11.0 1.0
Luis 15.0 1.0
您还可以映射几个值,其中任何一个都不存在的值都是 NaN
d = {key: value for l,value in zip([stream_0, stream_1], [0,1]) for key in l}
customer['STREAM'] = customer['FEAT'].map(d)
字典使用推导式来创建键值对。对于 stream_0
中的每个键我们给它赋值 0
,对于 stream_1
中的每个键我们分配一个值1
。理解起来有点复杂,所以更容易理解的方法是分别创建每个字典,然后将它们组合起来。
d_1 = {k: 0 for k in stream_0}
d_2 = {k: 1 for k in stream_1}
d = {**d_1, **d_2} # Combine
#{1: 0, 2: 1, 3: 0, 4: 1, 5: 0, 6: 1, 7: 1,
# 8: 0, 9: 1, 10: 0, 11: 1, 12: 0, 13: 1, 14: 0, 15: 1}
关于python - 来自包含 NaN 值的数据的 Pandas 数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61778820/