Python 迭代选择数据帧中的单元格并替换值
我有一个熊猫数据框,看起来像下面的示例:Python 迭代选择数据帧中的单元格并替换值,python,pandas,iteration,indices,Python,Pandas,Iteration,Indices,我有一个熊猫数据框,看起来像下面的示例: tags tag1 tag2 tag3 0 [a,b,c] 0 0 0 1 [a,b] 0 0 0 2 [b,d] 0 0 0 ... n [a,b,d] 0 0 0 我想将标记封装为tag1、tag2、tag3行
tags tag1 tag2 tag3
0 [a,b,c] 0 0 0
1 [a,b] 0 0 0
2 [b,d] 0 0 0
...
n [a,b,d] 0 0 0
我想将标记
封装为tag1、tag2、tag3
行中的1,如果它们存在于该行索引的标记
数组中
然而,我不太明白如何正确地迭代;到目前为止,我的想法如下:
for i, row in dataset.iterrows():
for tag in row[0]:
for column in range (1,4):
if dataset.iloc[:,column].index == tag:
dataset.set_value(i, column, 1)
但是,从该方法返回数据集时,列仍然全部为0值
谢谢大家! 看来您需要:
- 用于将列转换为字符串(如果包含列表)
- 用于删除
[]
最后通过以下方式将
df1
添加到原始DataFrame
:
试试
dataset=dataset.set_value(i,column,1)
?谢谢-效果很好,尽管它删除了我数据集的所有其余部分。我将把结果的内容合并到原始数据集中。美丽!非常感谢。
df1 = df['tags'].astype(str).str.strip('[]').str.get_dummies(', ')
print (df1)
'a' 'b' 'c' 'd'
0 1 1 1 0
1 1 1 0 0
2 0 1 0 1
3 1 1 0 1
df = pd.concat([df,df1], axis=1)
print (df)
tags tag1 tag2 tag3 'a' 'b' 'c' 'd'
0 [a, b, c] 0 0 0 1 1 1 0
1 [a, b] 0 0 0 1 1 0 0
2 [b, d] 0 0 0 0 1 0 1
3 [a, b, d] 0 0 0 1 1 0 1