我需要遍历数据帧一行中的列以找到第一个完全大写的单元格(在给定行中)。我需要对数据框中的所有行重复此操作,最后输出一个包含一列的数据框,每一行都带有相应的第一个大写字符串。
例如 - 这可能是输入数据框:
+-----+--------+--------+--------+------+
| 0 | 1 | 2 | 3 | 4 |
+-----+--------+--------+--------+------+
| a | Amount | SEQ | LTOTAL | None |
| BBc | LCALC | None | None | None |
| c | LCALC | None | None | None |
| Dea | RYR | LTOTAL | None | None |
+-----+--------+--------+--------+------+
我需要在单独的数据框中输出如下内容:
+-------+
| SEQ |
| LCALC |
| LCALC |
| RYR |
+-------+
请您参考如下方法:
如果需要通过isupper检查所有列测试值并将不匹配的值替换为NaNs,那么可能回填缺失值并通过iloc选择第一列:
df = df.where(df.applymap(lambda x: x.isupper())).bfill(axis=1).iloc[:, 0].to_frame('col')
print (df)
col
0 SEQ
1 LCALC
2 LCALC
3 RYR
编辑:
创建 df1,其中包含按匹配值位置排列的列,因此第一列是第一个较高的值,...:
#reshape by stack, None and NaNs columns are removed,
#remove second level of MultiIndex
s = df.stack().reset_index(level=1, drop=True)
#filter only upper values, convert to DataFrame
df1 = s[s.str.isupper()].rename_axis('idx').reset_index(name='val')
#create counter column for count first, second... columns
df1['g'] = df1.groupby('idx').cumcount()
#reshape by pivot and if necessary add non upper rows
df1 = df1.pivot('idx','g','val').reindex(df.index)
print (df1)
g 0 1
0 SEQ LTOTAL
1 LCALC NaN
2 LCALC NaN
3 RYR LTOTAL
first = df1[0].to_frame('col')
second = df1[1].to_frame('col')
print (first)
col
0 SEQ
1 LCALC
2 LCALC
3 RYR
print (second)
col
0 LTOTAL
1 NaN
2 NaN
3 LTOTAL
