python - 比较 >= 列,然后根据比较删除另一列,减 1 并执行直到满足条件
问题描述
我正在缓慢但肯定地学习这个 Python/Pandas,但大多数时候它让我争吵不休,把我扭来扭去。我正在做一个项目,该项目将比较两列(一次一行),然后将 lstrip 的操作应用于同一行的另一列。基本上,如果 [count column] 大于 [column1] 然后 lstrip [column2 (any numbers and/or .periods) ],然后 lstrip [column2 ('|') 一次,然后从 [count column] 中减去 1 和重新开始这个过程。这应该一直持续到“count”列号等于“column1”号然后停止。但是 'column2 中的所有字段都有不同的数字长度,有些字段的运行时间会比其他字段长。
目前,代码将运行并(同时)删除“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
解决方案
apply
您可以使用一个lambda
函数一次性完成,而不是多次执行逻辑。这个想法是先拆分|
,然后在切片基础上重新加入所有内容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
推荐阅读
- c++ - 什么时候为派生类初始化 vptr?
- javascript - 调用ajax后如何在新的HTML页面中显示结果
- regex - 匹配字符串中的不同模式
- python - Python 集花费的内存量逐步增加
- javascript - 在javascript数组中检查并转换具有条件的重复对象
- c# - 以泛型表达式和动作作为参数调用方法
- node.js - 如何在电子应用程序 windows/mac 中检查设备连接到哪个网络和 VPN?
- android - 将片段添加到 BackStack 不断抛出错误
- jqgrid - Free JqGrid - 网格不刷新
- electron - 限制电子应用程序只能安装在 Windows 7 及更高版本上?