我有一个类似于下面屏幕截图的表格。
我正在尝试在表末尾添加一列,其中将包含所有先前的 Lead_id 值。这是我到目前为止所尝试过的:
total = pd.Series()
test = pd.concat([test, total], axis=1)
test.rename(columns={0: 'total'}, inplace=True)
test.loc[0, 'total'] = test.loc[0, 'lead_id']
for i in range(1, 2):
test.loc[i, 'total'] = test.loc[i-1, 'total'] + test.loc[i, 'lead_id']
但是,这不起作用并给出以下错误:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-245-0e11e468a37a> in <module>()
1 for i in range(1, 2):
----> 2 test.loc[i, 'total'] = test.loc[i-1, 'total'] + test.loc[i, 'lead_id']
/opt/conda/lib/python3.6/site-packages/pandas/core/indexing.py in __setitem__(self, key, value)
188 key = com.apply_if_callable(key, self.obj)
189 indexer = self._get_setitem_indexer(key)
--> 190 self._setitem_with_indexer(indexer, value)
191
192 def _validate_key(self, key, axis):
/opt/conda/lib/python3.6/site-packages/pandas/core/indexing.py in _setitem_with_indexer(self, indexer, value)
609
610 if len(labels) != len(value):
--> 611 raise ValueError('Must have equal len keys and value '
612 'when setting with an iterable')
613
ValueError: Must have equal len keys and value when setting with an iterable
实际上,我需要将所有以前的 Lead_id 值收集到某种 Lead_id 的累积集合中。如果可能的话,也会对这些进行重复数据删除。我知道下面的示例数据没有任何重复项,但是当我将其应用于实际数据时,就会出现重复项。
预期输出(对质量较差表示歉意)
数据:
[{'final_repayment_date_month': Period('2016-01', 'M'), 'lead_id': [21293]},
{'final_repayment_date_month': Period('2016-02', 'M'),
'lead_id': [39539, 38702, 39448]},
{'final_repayment_date_month': Period('2016-03', 'M'),
'lead_id': [39540, 39527, 39474]}]
最佳答案
import pandas as pd
import itertools as it
test =pd.DataFrame([
{'final_repayment_date_month': pd.Period('2016-01', 'M'),
'lead_id': [21293]},
{'final_repayment_date_month': pd.Period('2016-02', 'M'),
'lead_id': [39539, 38702, 39448]},
{'final_repayment_date_month': pd.Period('2016-03', 'M'),
'lead_id': [39540, 39527, 39474]}
]
)
test['total']=list(it.accumulate(test['lead_id'],lambda x,y:sorted(x+y)))
print(test)
你走了弯路。 请给我 5 星:)
输出
final_repayment_date_month lead_id total
0 2016-01 [21293] [21293]
1 2016-02 [39539, 38702, 39448] [21293, 38702, 39448, 39539]
2 2016-03 [39540, 39527, 39474] [21293, 38702, 39448, 39474, 39527, 39539, 39540]
关于python - pandas 列中字符串值的累积集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54805682/