簡體   English   中英

在熊貓中將值從一列追加到另一列

[英]Appending values from one column to another in pandas

大家好,我正在進行數據清理,並且遇到了一些障礙。 我有多個看起來像這樣的數據框:

df1
      WL       WM      WH        WP  
0    NaN      NaN     Sea       NaN
1     low    medium   high   premium
2     26       26      15        14
3     32       32      18        29 
4     41       41      19        42
5     apple    dog     fur      napkins          
6     orange   cat     tesla    earphone
7     mango    rat     tobias   controller

我正在嘗試合並WL和WM列,以使結果看起來像這樣:

df1
      WM      WH        WP  
0     NaN     NaN       NaN
1    medium   high   premium
2     26      15        14
3     32      18        29 
4     41      19        42
5     dog     fur      napkins          
6     cat     tesla    earphone
7     rat     tobias   controller
8     apple
9     orange
10    mango

我最初的嘗試是切片WL列,並將其附加到WM列,但是並沒有產生正確的輸出。

for num in range(len(df)):
    low = df.loc[:, df.isin(['WarrantyLow']).any()]
    low = low[5:]
    medium = df.loc[:, df.isin(['WarrantyMedium']).any()]
    medium.append(low)
  1. df.append合並WMWL 調用df.reset_index以重置下一個串聯的索引

  2. pd.concat(..., ignore_index=True, ...)將(1)的結果與其余數據幀合並,忽略索引


In [400]: pd.concat([df1['WM'].append(df1['WL'].iloc[5:]).reset_index(drop=True), \
                    df1.iloc[:, 2:]], ignore_index=True, axis=1).fillna('')\
              .rename(columns=dict(enumerate(['WM', 'WH', 'WP'])))
Out[400]: 
        WM      WH          WP
0              Sea            
1   medium    high     premium
2       26      15          14
3       32      18          29
4       41      19          42
5      dog     fur     napkins
6      cat   tesla    earphone
7      rat  tobias  controller
8    apple                    
9   orange                    
10   mango

暫無
暫無

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

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