【问题标题】:How to concatenate multiple Pandas Series into one row?如何将多个熊猫系列串联成一行?
【发布时间】:2019-09-30 07:50:24
【问题描述】:

目标:我有两个Pandas Series。在每个我想应用一个函数,为我提供一些列的汇总统计信息(如sumcount 等)。所有这些都嵌入在 for each` 循环中。例如:

DataFrame1
    Id      V1       V2    
    0       3        2
    1       2        1

DataFrame2
    Id      T1       T2    
    0       4        2
    1       5        2

结果(计数任务)假设为:

DataFrameGoal
    Id      V1       V2      T1       T2  
    0       2        2       2        2

我的代码运行良好,但我得到的解决方案是:

DataFrameGoal
    Id      V1       V2      T1       T2  
    0       2        2       NaN      NaN
    1       NaN      NaN     2        2

我的代码:

import pandas as pd
import numpy as np
df1 = pd.DataFrame({'a' : np.random.randn(6),
                 'b' : np.random.randn(6),
                 'c' : np.random.randn(6)})

df2 = pd.DataFrame({'d' : np.random.randn(6),
                 'e' : np.random.randn(6),
                 'f' : np.random.randn(6)})

def mysum(col):
    return col.count()

lst = []
lst.append(df1)
lst.append(df2)

myDf = pd.DataFrame()

for el in lst:
    test = el.apply(lambda cols: mysum(cols))
    myDf = myDf.append(test, ignore_index=True)

print(myDf)

谁能帮助我获得我想要的结果?我也试过.assign,但这也不能解决我的问题。 P.S.:我知道像 count 或 sum 这样简单的事情可以很容易地完成,但我有一些复杂的任务,这只是一个简单的例子。

【问题讨论】:

    标签: python pandas concatenation series


    【解决方案1】:

    很难说问题是来自连接数据帧还是来自mySum()。不过你可以试试:

    myDf = (pd.concat(el.apply(lambda cols: mySum(cols)) 
                       for el in [df1,df2])
              .to_frame().T)
    

    【讨论】:

      【解决方案2】:

      试试这个

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

      然后应用你想要的任何功能。

      【讨论】:

        猜你喜欢
        • 2014-06-26
        • 2016-03-14
        • 2021-06-23
        • 1970-01-01
        • 2013-08-06
        • 2019-05-01
        • 2021-06-04
        • 1970-01-01
        • 2021-09-21
        相关资源
        最近更新 更多