Skip to main content
 首页 » 编程设计

python之遍历 pandas DataFrame 中的选择单元格并替换值

2024年10月01日8Free-Thinker

我有一个类似于以下示例的 pandas DataFrame:

      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 

如果 tags 数组中存在该行索引。

但是,我不太清楚如何正确地迭代;到目前为止,我的想法如下:

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 = 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 

最后将 df1 添加到原始 DataFrame by concat :

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