【发布时间】:2021-10-21 03:13:40
【问题描述】:
在开始之前,感谢大家的时间和知识。 如果您有更好的标题推荐,请告诉我。
我有一个格式如下的数据框:
index join file
0 inner join a
1 on xxx a
2 inner join on yyy b
3 left join c
我正在运行一个循环以将以“on”或“and”开头的行附加到上面的行。像这样:
result = []
for j in df['join']:
if j.startswith('and') and len(result) > 0:
result[-1] += ' ' + j
elif j.startswith('on') and len(result) > 0:
result[-1] += ' ' + j
else:
result.append(j)
df = pd.DataFrame(result)
循环正常运行并返回:
index join
0 inner join on xxx
1 inner join on yyy
2 left join
但是,循环没有引入“文件”字段。我将如何做到这一点?
【问题讨论】:
-
您正在迭代一列
for j in df['join']:使用for ind, row, in df.iterrows(): -
这是作业吗?我很确定我最近看到了类似的东西。
-
不是为了作业,我只是不擅长 python - 另外,如果我没有正确使用该网站,请告诉我。
-
嗯,经验法则是您应该避免在 pandas 中执行循环。尽可能使用
groupby或矢量运算。如果my answer 适合您的需要,请告诉我。
标签: python pandas list loops append