更有效地执行嵌套python循环

2024-10-02 00:26:21 发布

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

我在这里看过其他的解释,但都不太合适。 解包代码可以工作,但速度非常慢。有没有更好的方法可以和python一起使用。我看不出我怎么能在这里工作。 任何建议都会很有帮助。你知道吗

import pandas as pd

df = pd.DataFrame(data={'a':['A1 + A3','B4 + A4 + D2','C2 + D2'],'b':['L700 + 
          L800','G700','L2600 + L900'],'c':['6','7','8']})
df

    a   b   c
0   A1 + A3 L700 + L800     6
1   B4 + A4 + D2    G700    7
2   C2 + D2 L2600 + L900    8

df2 = pd.DataFrame(columns = df.columns)
for index, row in df.iterrows():
    userLabel = row.loc['a']
    cells = userLabel.split('+') 

    ID = row.loc['b']
    tech = ID.split('+')     
    i = 0
    for cell in cells:

        cell = cell.strip()
        row.loc['a'] = cell
        if i > len(tech)-1:
            i = i-1
        row.loc['b'] = tech[i]
        df2.loc[len(df2)] = row
        i += 1

df2

    a   b   c
0   A1  L700    6
1   A3  L800    6
2   B4  G700    7
3   A4  G700    7
4   D2  G700    7
5   C2  L2600   8
6   D2  L900    8

Tags: dfa1cellloca3a4rowd2
1条回答
网友
1楼 · 发布于 2024-10-02 00:26:21

用途:

df = (df.set_index('c')
        .stack()
        .str.split('\s+\+\s+', expand=True)
        .stack()
        .unstack(1)
        .ffill()
        .reset_index(level=1, drop=True)
        .reset_index()
        .reindex(columns=['a','b','c'])
        )
print (df)
    a      b  c
0  A1   L700  6
1  A3   L800  6
2  B4   G700  7
3  A4   G700  7
4  D2   G700  7
5  C2  L2600  8
6  C2   L900  8

解释:

  1. 拆分列的第一个^{}用于拆分
  2. MultiIndexSeries重塑^{}
  3. ^{}按regex-nees escape +为每行创建DataFrame,对于一个或多个空格使用\s+
  4. ^{}^{}对第二级列进行整形
  5. ffill向前填充NaNs
  6. 通过^{}清理数据
  7. 如果列的顺序很重要,则添加^{}

相关问题 更多 >

    热门问题