簡體   English   中英

通過使用pandas將兩列組合到一列來重建數據幀

[英]To rebuild a dataframe by combining two columns into one column by using pandas

我想通過將兩列組合成一列來重建我的數據幀,例如,

>>>df.set_index('df1')  
        0 1 2 3 4 5
df1
GroupA  A D G J M P
GroupB  B E H K N Q
GroupC  C F I L O R   #It is my dataframe.

然后我想看看我的結果如下。

 >>>print result
    df1     0  1  2
    GroupA  AD GJ MP  
    GroupB  BE HK NQ
    GroupC  CF IL OR  

#which means column0 is combined with column1, and 2+3, and 4+5......etc

我只知道我可以使用concat()來組合列並使用apply(lambda xxx...)來設置合適的函數。

有沒有人可以通過在python中使用pandas給我一個提示或知道如何獲得它? 謝謝,

你要求做的有點奇怪,但基本上我們可以按2步迭代列,然后在df的子部分調用sum並傳遞axis=1 ,這將連接str值。 一個棘手的問題是你的列是數字,當使用方括號時,它會嘗試將列名解析為str,這意味着col+1將不起作用,這就是我將它轉換為int

In [32]:

dfnew = pd.DataFrame()
for col in df.columns[::2]:
    c = int(col)
    dfnew[col] = df[[c,c+1]].sum(axis=1)
dfnew
Out[32]:
         0   2   4
df1               
GroupA  AD  GJ  MP
GroupB  BE  HK  NQ
GroupC  CF  IL  OR

編輯

通用方法使用列數的長度來生成整數索引以索引到列數組中並從中提取列名以執行選擇,這將適用於您的df以及df具有str名稱的位置:

In [26]:

dfnew = pd.DataFrame()
for i in range(len(df.columns))[::2]:
    col_1 = df.columns[i]
    col_2 = df.columns[i+1]
    dfnew[col_1] = df[[col_1,col_2]].sum(axis=1)
dfnew
Out[26]:
         0   2   4
df1               
GroupA  AD  GJ  MP
GroupB  BE  HK  NQ
GroupC  CF  IL  OR

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM