如何正确使用while循环?

原子商店

我有一个数据框:

SIN1       SIN2      SIN3
4778       5633      4343

我试过了,

count_col = len(df1.columns)

check=1

while check<=count_col:
    check_str = str(check)
    check_for_column = "SIN"+check_str in df1
    name = "SIN"+check_str
    
    if check_for_column == True:
        df1[name] = df1[name].astype(str)
        df1['SIN1'] = df1['SIN1'] + ',' + df1[name]

    if check == count_col:
        break
    
    check += 1

df1[['SIN1']]

由此可见 4778,4343,4778,4343.................

当我尝试时,

check=1

while check<=count_col:
    check_str = str(check)
    check_for_column = "SIN"+check_str in df1
    name = "SIN"+check_str
    
   

    if check == count_col:
        break
    
    check += 1

if check_for_column == True:
     df1[name] = df1[name].astype(str)
     df1['SIN1'] = df1['SIN1'] + ',' + df1[name]

df1[['SIN1']]

由此可见 4778,4343

我想要的结果是 4778,5633,4343

请不要建议直接与 ',' 连接的方法。

我使用 while 循环是因为可以没有任何 SIN 列。

在这种情况下如何正确使用while循环?

科拉连

使用apply加入列值:

>>> df['SIN'] = df.astype(str).apply(lambda x: ','.join(x), axis=1)
>>> df

   SIN1  SIN2  SIN3             SIN
0  4778  5633  4343  4778,5633,4343

要选择像 那样的列子集SINxx,请使用filter

df.filter(like='SIN')  # or df.filter(regex='SIN\d+')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章