我有Dataframe包含列+“ Order”列,该列具有整数唯一数字,并且某些行为零。
我需要从“订单”值的最大值开始用增量数更新零。
例如:
df ['Order'] = 4的最大值,并且有3条记录df ['Order'] == 0,那么那3个具有0值的行需要用5、6、7填充。
我尝试了以下脚本:
Dimension_Items = {'Col1':['A', 'B', 'C', 'D', 'E', 'F'], 'Order':[0,2,3,4,0,0]}
Dimension_Items = pd.DataFrame.from_dict(Dimension_Items)
Max_Order = Dimension_Items['Order'].max()
Dimension_Items.loc[Dimension_Items['Order'] == 0, 'Order'] = range(Max_Order+1, len(Dimension_Items)+1)
错误:
Traceback (most recent call last):
Dimension_Items.loc[Dimension_Items['Order'] == 0, 'Order'] = range(Max_Order+1, len(Dimension_Items)+1)
File "C:\Python36\lib\site-packages\pandas\core\indexing.py", line 189, in __setitem__
self._setitem_with_indexer(indexer, value)
File "C:\Python36\lib\site-packages\pandas\core\indexing.py", line 606, in _setitem_with_indexer
raise ValueError('Must have equal len keys and value '
ValueError: Must have equal len keys and value when setting with an iterable
出现错误,请对此提供帮助
答案 0 :(得分:1)
间谍。
您可以遍历DataFrame来查找Order = 0的项目,然后使用max_order + 1更新每个Order。
import pandas as pd
data = {
'Col1': ['A', 'B', 'C', 'D', 'E', 'F'],
'Order': [0, 2, 3, 4, 0, 0]
}
df = pd.DataFrame(data)
max_order = df['Order'].max()
for i in range(len(df)):
if df.loc[i, 'Order'] == 0:
df.loc[i, 'Order'] = max_order + 1
max_order += 1
df.head()
输出:
Order Value
0 A 5
1 B 2
2 C 3
3 D 4
4 E 6
希望这会有所帮助。
答案 1 :(得分:1)
因此,如果我理解正确,我们可以隔离零,然后使用列表中的值填充零。
l = range(df.Order.max() + 1, df.Order.max() + df.loc[df.Order == 0, 'Order'].size + 1)
df.loc[df.Order == 0, 'Order'] = l
Col1 Order
0 A 5
1 B 2
2 C 3
3 D 4
4 E 6
5 F 7