如何遍历行中的列以找到满足某些条件的第一个列

2024-03-28 23:11:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要遍历dataframe行中的列,以找到第一个完全大写的单元格(在给定行中)。我需要对dataframe中的所有行重复此操作,最后输出一个包含一列的dataframe,每行包含相应的第一个大写字符串。你知道吗

例如,这可能是输入数据帧:

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

Tags: 数据字符串nonedataframeamountseqbbc大写
3条回答

如果需要按isupper检查所有列的测试值,并将不匹配的值替换为NaN,这样就可以用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

您可以使用

column = list()

for _, row in df.iterrows():
    for item in row:
        if item.isupper():
            column.append(item)
            break
    else:
        column.append(numpy.nan)

new_df = pandas.DataFrame(column)

使用以下代码遍历该行,并在该行中的all caps单元格的第一个实例处中断

import pandas as pd
l=[]
for index,row in df.iterrows():
    for i in row:
            if(i.isuppercase()):
                    l.append(i)
                    break
new_df = pandas.DataFrame(l)

相关问题 更多 >