如何正确使用while循环?
How to use while loop properly?
我有一个数据框:
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循环?
此代码获取所有包含 SIN
的列,将值连接为字符串,并将其分配给新列 SIN
.
sin_cols = [ ( 'SIN' in col ) for col in df.columns ]
sdf = df.loc[ :, sin_cols ]
df[ 'SIN' ] = sdf.apply( lambda x: ', '.join( x.values.astype( str ) ), axis = 1 )
df
之前
id
T
SIN1
SIN2
Q
SIN3
0
8
3
6
9
8
1
1
6
1
7
1
2
5
2
4
8
6
df
在
之后
id
T
SIN1
SIN2
Q
SIN3
SIN
0
8
3
6
9
8
3, 6, 8
1
1
6
1
7
1
6, 1, 1
2
5
2
4
8
6
2, 4, 6
使用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
要 select 列的子集,例如 SINxx
,请使用 filter
:
df.filter(like='SIN') # or df.filter(regex='SIN\d+')
我有一个数据框:
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循环?
此代码获取所有包含 SIN
的列,将值连接为字符串,并将其分配给新列 SIN
.
sin_cols = [ ( 'SIN' in col ) for col in df.columns ]
sdf = df.loc[ :, sin_cols ]
df[ 'SIN' ] = sdf.apply( lambda x: ', '.join( x.values.astype( str ) ), axis = 1 )
df
之前
id | T | SIN1 | SIN2 | Q | SIN3 |
---|---|---|---|---|---|
0 | 8 | 3 | 6 | 9 | 8 |
1 | 1 | 6 | 1 | 7 | 1 |
2 | 5 | 2 | 4 | 8 | 6 |
df
在
id | T | SIN1 | SIN2 | Q | SIN3 | SIN |
---|---|---|---|---|---|---|
0 | 8 | 3 | 6 | 9 | 8 | 3, 6, 8 |
1 | 1 | 6 | 1 | 7 | 1 | 6, 1, 1 |
2 | 5 | 2 | 4 | 8 | 6 | 2, 4, 6 |
使用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
要 select 列的子集,例如 SINxx
,请使用 filter
:
df.filter(like='SIN') # or df.filter(regex='SIN\d+')