【问题标题】:compare >= columns, then lstrip another column based on compare, subtract 1 and do until condition is met比较 >= 列,然后根据比较删除另一列,减 1 并执行直到满足条件
【发布时间】:2020-07-04 05:08:06
【问题描述】:

我正在缓慢但肯定地学习这个 Python/Pandas,但大多数时候它让我争吵不休,把我弄得一团糟。我正在开发一个项目,该项目将比较两列(一次一行),然后将 lstrip 的操作应用于同一行的另一列。基本上,如果 [count column] 大于 [column1] 然后 lstrip [column2 (any numbers and/or .periods) ],然后 lstrip [column2 ('|') 一次,然后从 [count column] 中减去 1 和重新开始这个过程。这应该一直持续到“count”列号等于“column1”号然后停止。但是 'column2 中的所有字段都有不同的数字长度,有些会比其他字段运行时间更长。

目前,代码将运行并 lstrip 'column2' 中的所有行(同时),并从 'count' 列中的所有行中减去 1。它将继续运行,直到“计数”列达到负数。这意味着当“count”列等于“column1”时,它不会停止操作(针对该行)。

我的想法是一次处理一行,当“计数”列等于 column1 时,然后继续向下一行并重新开始该过程。冲洗并重复直到完成。但是,在尝试查找示例时,我发现以下链接表明 pandas 旨在一次通过操作运行整个系列(列),而不是我认为一次一行的逻辑。

<http://shorturl.at/acvIL>

我感谢任何可以帮助教人钓鱼的人。感谢您抽出宝贵时间,如果您有任何问题,请告诉我。

import pandas as pd
from pandas import DataFrame, Series
import numpy as np

# get starting excel file - Working
df = pd.read_excel("E:\Book11.xlsx")

# inserts 'count' column  into last position. - Working
df.insert(2, 'count', '')

# counts the number of '|' spec-char in the 'col2' column and places sum into 'count' column . - 
# Working
f = df['column2'].str.count('\|')
df.loc['column2'] = df['count'] = f

# compares 'count' column number greater than 'column1' number to start condition
for count, column1 in zip(df.iloc[:, 2], df.iloc[:, 0]):

# if condition is true, then lstrip any (0-9.)chars, then lstrip('\|') spec-char,
# then subtract 1 from 'count' column and test again (all rows).
    df['column2'] = df['column2'].astype(str).str.lstrip('0123456789.')
    df['column2'] = df['column2'].astype(str).str.lstrip('\|')
    df['count'] = df['count'] - 1



# 'count' column has different numbers than 'column1' column so some rows will complete
# sooner than other rows. But all rows at different times and only if 'count' column reaches == 
# (equal) to 'column1' column .

print(df)



Before:
column1   column2                                                        count
7         0|0|0|0|0|0|0|0|0|0|0|0|0|0|0                                  14
2         369|369|219|219|219                                            4
3         413.1|413.1|413.1|413.1|413.1|413.1                            5
6         228.65|228.65|228.65|322.15|322.15|322.15|228.65|228.65        7
4         359|359|359|359|359                                            4


Finished Product:
column1   column2                                                        count
7         0|0|0|0|0|0|0|0                                                7
2         369|369|219                                                    2
3         413.1|413.1|413.1|413.1                                        3
6         228.65|322.15|322.15|322.15|228.65|228.65|225                  6
4         359|359|359|359|359                                            4 

【问题讨论】:

    标签: python pandas vectorization series strip


    【解决方案1】:

    您可以使用applylambda 函数一次性完成,而不是多次执行逻辑。想法是在| 上拆分,然后在基于column1 切片后再次加入所有内容。

    df['column1'] = df['column1'].astype(int)
    df['column2'] = df.apply(lambda x: '|'.join(x.column2.split('|')[:x.column1 + 1]), axis=1)
    
       column1                                           column2  count
    0        7                                   0|0|0|0|0|0|0|0      7
    1        2                                       369|369|219      2
    2        3                           413.1|413.1|413.1|413.1      3
    3        6  228.65|228.65|228.65|322.15|322.15|322.15|228.65      6
    4        4                               359|359|359|359|359      4
    

    【讨论】:

    • 嗨 ScootCork,现在正在看这个。我喜欢这个理想..!我替换了最后三行(就在 print(df) 上方并删除了 df['columns'] 行并收到一个错误。假设这是它的去向?错误:TypeError:切片索引必须是整数或 None 或有一个 index 方法.. 这让我觉得 excel 工作表是以字符串或其他形式出现的。读取的错误必须是整数,所以我该如何测试呢?你的想法是什么?
    • 因此查看在 column1 和 count 列中遇到的 excel 文件,有小数点后跟六个零。我正在阅读如何将这些更改为整数,以便我可以运行您的代码。
    • 将 cxast 的答案调整为 int,您实际上也不需要计数,所以稍微简化了一点。
    • 鉴于您的问题,这是一个可能的解决方案,如果它不起作用,请说明它为什么不起作用或调整/澄清您的问题。最好有一个最小的可重现示例。这样也可以帮助其他有类似问题的人。
    • ScootCork,我能够使用原始 DF 来实现它。很高兴知道我编写的整个代码都是无关紧要的并且不需要的,我们可以来回避免这种情况。然而,在花了一些时间试图理解 lambda & apply 之后,我开始破译你的代码。问题实际上是我计算“|”的代码和计数列中的 str 语句。您的代码无法将 column2 更改为整数。所以我完全摆脱了我的代码,只使用了你的代码,稍作调整。感谢您让我看到 smtg diff。
    猜你喜欢
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多