[英]How to concatenate multiple Pandas Series into one row?
目標:我有兩個Pandas Series
。 我想在每個函數上應用一個函數,該函數為列提供一些匯總統計信息(例如sum
, count
等)。 所有這些都嵌入在for``循環中。 例如:
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
但這也無法解決我的問題。 PS:我知道簡單的事情(例如計數或總和)可以很容易地完成,但是我有一些復雜的任務,這只是一個簡單的例子。
嘗試這個
pd.concat([df1,df2], axis=1)
然后應用您想要的任何功能。
很難說問題出在連接數據幀還是形成mySum()
。 但是您可以嘗試:
myDf = (pd.concat(el.apply(lambda cols: mySum(cols))
for el in [df1,df2])
.to_frame().T)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.