使用for循环附加 pandas 系列 [英] To append pandas series using for loop

查看:95
本文介绍了使用for循环附加 pandas 系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个系列和列表:

df1 = pd.Series(['a','b','c','d'])
df2 = pd.Series(['e','f','g','h'])
df3 = pd.Series(['i','j','k','l'])


df1
0    a
1    b
2    c
3    d
df2
0  e
1  f
2  g
3  h

df3
0 i
1 j
3 k
4 l

list = [df1,df2,df3]

我想使用这样的循环附加系列:

I want to append series using loop like this:

 df1  df2   df3
0 a     e    i
1 b     f    j
2 c     g    k
3 d     h    l

我该如何实现?

我尝试过这样,但是失败了:

I tried like this but failed:

for i in dflist:
    tempdata = pd.DataFrame([])
    mstdf = tempdata.append(i, ignore_index= True)
    print(mstdf)


   0  1  2  3
0  a  b  c  d
   0  1  2  3
0  e  f  g  h
   0  1  2  3
0  i  j  k  l

我已经参考了pandas.DataFrame.append文档,并且还研究了一些堆栈问题.但是我无法解决这个问题.

I have already referenced pandas.DataFrame.append documentation and I've also looked at some of the stack's questions. But I can not solve this problem.

python-在pandas.DataFrame中添加一行-代码日志 python-将列表或系列作为一行追加到pandas DataFrame ... python-如何在for循环中将pandas数据帧中的行追加...

python - add one row in a pandas.DataFrame - Stack Overflow python - Appending a list or series to a pandas DataFrame as a row ... python - How to append rows in a pandas dataframe in a for loop ...

推荐答案

如果可以的话,我会使用pd.concat

I'd use pd.concat if I could

pd.concat([df1, df2, df3], axis=1, keys=['df1', 'df2', 'df3'])

  df1 df2 df3
0   a   e   i
1   b   f   j
2   c   g   k
3   d   h   l

您还可以将pd.concat与字典一起使用

You could also use pd.concat with a dictionary

pd.concat({'df1': df1, 'df2': df2, 'df3': df3}, axis=1)

  df1 df2 df3
0   a   e   i
1   b   f   j
2   c   g   k
3   d   h   l


但是如果您必须使用循环


But if you must use a loop

df_agg = None

for name, df in zip(['df1', 'df2', 'df3'], [df1, df2, df3]):
    if df_agg is None:
        df_agg = df.to_frame(name)
    else:
        df_agg[name] = df

df_agg

  df1 df2 df3
0   a   e   i
1   b   f   j
2   c   g   k
3   d   h   l

这篇关于使用for循环附加 pandas 系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆