我有一个看起来像这样的数据框:
df = pd.DataFrame(np.nan, index=[0,1,2,3], columns=['A','B','C'])
df.iloc[0,0] = 'a'
df.iloc[1,0] = 'b'
df.iloc[1,1] = 'c'
df.iloc[2,0] = 'b'
df.iloc[3,0] = 'c'
df.iloc[3,1] = 'b'
df.iloc[3,2] = 'd'
df
out : A B C
0 a NaN NaN
1 b c NaN
2 b NaN NaN
3 c b d
我想向其中添加新列,其名称是数据帧内的值(此处 'a'
,'b'
,'c '
和'd'
)。这些列是二进制的,反射(reflect)值 'a'
、'b'
、'c'
和 'd'
在行中。
在一张图片中,我想要的输出是:
A B C a b c d
0 a NaN NaN 1 0 0 0
1 b c NaN 0 1 1 0
2 b NaN NaN 0 1 0 0
3 c b d 0 1 1 1
为此,我首先创建填充零的列:
cols = pd.Series(df.values.ravel()).value_counts().index
for col in cols:
df[col] = 0
(它不会以正确的顺序创建列,但这并不重要)
然后我...在行和列上使用循环...
for row in df.index:
for col in cols:
if col in df.loc[row].values:
df.ix[row,col] = 1
你会明白为什么我正在寻找另一种方法来做到这一点,即使我的数据帧相对较小(76k 行),它仍然需要大约 8 分钟,这太长了。
有什么想法吗?
最佳答案
您正在寻找get_dummies
。这里我选择使用.str
version :
df.fillna('', inplace=True)
(df.A + '|' + df.B + '|' + df.C).str.get_dummies()
输出:
a b c d
0 1 0 0 0
1 0 1 1 0
2 0 1 0 0
3 0 1 1 1
关于python - 根据其值的条件在数据框中创建二进制列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37456971/