【发布时间】:2023-03-24 03:31:01
【问题描述】:
我有一个如下所示的数据框
+-----------+----------+-------+-------+-----+----------+-----------+
| InvoiceNo | totalamt | Item# | price | qty | MainCode | ProdTotal |
+-----------+----------+-------+-------+-----+----------+-----------+
| Inv_001 | 1720 | 260 | 1500 | 1 | 0 | 1500 |
| Inv_001 | 1720 | 777 | 100 | 1 | 260 | 100 |
| Inv_001 | 1720 | 888 | 120 | 1 | 260 | 120 |
| Inv_002 | 1160 | 360 | 700 | 1 | 0 | 700 |
| Inv_002 | 1160 | 777 | 100 | 1 | 360 | 100 |
| Inv_002 | 1160 | 888 | 120 | 1 | 360 | 120 |
| Inv_002 | 1160 | 999 | 140 | 1 | 360 | 140 |
| Inv_002 | 1160 | 111 | 100 | 1 | 0 | 100 |
+-----------+----------+-------+-------+-----+----------+-----------+
我想添加ProdTotal 值,其MainCode 等于Item#。
受到我为question 得到的答案的启发,我设法产生了下面提到的所需输出
+-----------+----------+-------+-------+-----+----------+-----------+
| InvoiceNo | totalamt | Item# | price | qty | MainCode | ProdTotal |
+-----------+----------+-------+-------+-----+----------+-----------+
| Inv_001 | 1720 | 260 | 1720 | 1 | 0 | 1720 |
| Inv_002 | 1160 | 360 | 1060 | 1 | 0 | 1060 |
| Inv_002 | 1160 | 111 | 100 | 1 | 0 | 100 |
+-----------+----------+-------+-------+-----+----------+-----------+
使用下面的代码
df = pd.read_csv('data.csv')
df_grouped = dict(tuple(df.groupby(['InvoiceNo'])))
remove_index= []
ids = 0
for x in df_grouped:
for index, row in df_grouped[x].iterrows():
ids += 1
try:
main_code_data = df_grouped[x].loc[df_grouped[x]['MainCode'] == row['Item#']]
length = len(main_code_data['Item#'])
iterator = 0
index_value = 0
for i in range(len(df_grouped[x].index)):
index_value += df_grouped[x].at[index + iterator, 'ProdTotal']
df.at[index, 'ProdTotal'] = index_value
iterator += 1
for item in main_code_data.index:
remove_index.append(item)
except:
pass
df = df.drop(remove_index)
但是数据包含数百万行,并且这段代码运行速度非常慢。来自其他成员的简短谷歌搜索和 cmets,我知道 iterrows() 正在使代码运行缓慢。如何替换 iterrows() 以使我的代码更高效、更 Python 化?
【问题讨论】:
-
为什么不为零,没有一行的主代码等于项目编号。你的意思是把它们加起来吗?
-
什么应该是零? @ifly6
-
MainCode等于每个InvoiceNo中的Item#。例如:在Inv_001,Item# 777 888有MainCode 260。所以这些项目是260的一部分 -
但在您的示例数据框中,没有一个
MainCode值等于Item#。 -
@HS-nebula 专栏
Item#。将此视为主要产品和其他项目(例如Inv_001777, 888和Inv_002777 888 999)是与此相关的子产品。