【发布时间】:2019-02-03 10:42:18
【问题描述】:
我正在尝试根据收到的报告制作非规范化数据框。我需要将记录分配给一个组,该组来自一行,其中包含随机文本和组名称之间的 nan。满足条件时如何重写这些行值?我写的循环似乎只在满足条件时才覆盖下一个值,并且在满足下一个条件之前不会这样做。请参阅下面我的数据和代码示例。本质上,我需要这些行是 Primary、Secondary 或我决定的任何其他组,但它必须运行到下一个指定的组被命中。
当前数据:
Primary
Week#
1
nan
nan
nan
2
nan
nan
nan
Secondary
Week#
1
nan
nan
nan
2
nan
nan
nan
代码:
for index, obj in enumerate(df['col0']):
l = len(df['col0'])
if obj == 'Primary':
if index > 0:
previous = df['col0'][index - 1]
if index < (l - 1):
next_ = df['col0'][index + 1]
next_ = obj
print (next_, obj)
if obj == 'Secondary':
if index > 0:
previous = df['col0'][index - 1]
if index < (l - 1):
next_ = df['col0'][index + 1]
next_ = obj
print (next_, obj)
预期输出:
Primary
Primary
Primary
Primary
Primary
Primary
Primary
Primary
Primary
Primary
Secondary
Secondary
Secondary
Secondary
Secondary
Secondary
Secondary
Secondary
Secondary
Secondary
【问题讨论】:
-
我不确定我是否完全理解你想要实现的目标,但有两点很突出:1. 你在没有使用它的情况下为
previous赋值,而你'连续两次重新分配给next_,所以next_ = df['col0'][index + 1]总是被next_ = obj覆盖 -
我建议在您的问题中将示例数据与代码分开。我假设它们来自不同的文件,但现在示例数据部分看起来像格式错误的 Python 代码。也许你可以包括你得到的输出,以及你期望的输出?
标签: python-3.x loops iterator grouping conditional-statements