【发布时间】: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