【问题标题】:Looping over dataframe only returns one column [duplicate]循环数据帧只返回一列[重复]
【发布时间】: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


【解决方案1】:

您可以检查不以“on”开头的行并应用cumsum 将那些以“on”开头的行与上一行分组。最后分组加入:

(df.groupby((~df['join'].str.startswith('on ')).cumsum())
   ['join'].apply(' '.join)
   .reset_index(drop=True) # optional, to have index starting with 0
)

输出:

join
0    inner join on xxx
1    inner join on yyy
2            left join
Name: join, dtype: object

要应用于所有列,请使用agg

(df.groupby((~df['join'].str.startswith('on ')).cumsum())
   .agg(' '.join)
   .reset_index(drop=True)
)

输出:

                join file
0  inner join on xxx  a a
1  inner join on yyy    b
2          left join    c

您甚至可以对每列应用不同的操作:

(df.groupby((~df['join'].str.startswith('on ')).cumsum())
   .agg({'join': ' '.join, 'file': 'first'})
   .reset_index(drop=True)
)

输出:

                join file
0  inner join on xxx    a
1  inner join on yyy    b
2          left join    c

【讨论】:

  • 谢谢!我只是查看了 cumsum 和 groupby 的工作方式。我将继续使用这些。感谢您的帮助
猜你喜欢
  • 2013-05-05
  • 2016-12-17
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-21
  • 1970-01-01
相关资源
最近更新 更多