iT邦幫忙

1

Python Pandas 資料切割與複製!!

mackuo 2019-10-24 10:55:0213307 瀏覽
  • 分享至 

  • xImage

小弟Python新手,請各位先進指導。
感謝!!


問題:
得獎專題共10組,每組可能1-5人。原始資料的示意如下:
https://ithelp.ithome.com.tw/upload/images/20191024/20122335SYnpAGGJXm.png

預期的解決方式:
將小組成員切割成個別的得獎人,並在備註中註明與其他人合作。
如小組成員只有1人,則備註為空白。預期程式處理結果如下:
https://ithelp.ithome.com.tw/upload/images/20191024/20122335lYmmKJf8bq.png

問題檔案下載

抱歉,新手剛來,不了解守則。
自己寫了一段代碼,想法是先計算「,」的次數算出合作人數。
如果合作人數不是0,就複製那一列的合作人數的次數,
複製完了後,再切割小組成員,搬到得獎人員處。

目前就已經卡在如何依照合作人數複製列了。

import pandas as pd
import numpy as np

Location='sample.xlsx'

df = pd.read_excel(Location)
df['合作人數'] = df['小組成員'].str.count(',')

df

https://ithelp.ithome.com.tw/upload/images/20191024/201223350TbqEI4hwV.png

https://ithelp.ithome.com.tw/upload/images/20191024/201223350RktUh8WYL.png

lens = df.小組成員.str.split(',').str.len()
df.set_index('組別').reindex(df.組別.repeat(lens)).reset_index()

https://ithelp.ithome.com.tw/upload/images/20191024/20122335PyF8suXAS0.png

感謝ccutmis前輩無私的解答!!

我把問題放在國外的網站,得到我無法想像的code。
真是令人汗顏。

這是要答案了吧,不是指導了吧。
直接將題目放上來。也不說說你的問題在哪。(全部都是問題???)

這.........我該怎麼說呢???是不是拿著「指導」用意要答案??
這不是學習的態度吧。根本就是作業題。
ccutmis iT邦高手 2 級 ‧ 2019-10-24 13:03:14 檢舉
完成了!!!
http://www.web3d.url.tw/ITHELP/tmp/pandasTest.png

因為樓主提問沒貼源碼只貼題目,我這邊也只貼結果不貼源碼了^^"
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
ccutmis
iT邦高手 2 級 ‧ 2019-10-24 15:05:50
import pandas as pd
import numpy as np

def memberWithoutMe(member,me):
    tmpStr = '與「'
    count = 0
    for i in member:
        if i != me:
            if count>0:
                tmpStr = tmpStr + ","
            tmpStr = tmpStr + i
        count=count+1
    tmpStr = tmpStr + '」合作'
    return tmpStr

Location='sample.xlsx'
df = pd.read_excel(Location)

new_sample0=df[~df['小組成員'].str.contains(",")]
#小組成員只有一人的先撈出來並處理nan及得獎人員欄位
new_sample0=new_sample0.replace(np.nan, '', regex=True)
new_sample0['得獎人員']=new_sample0['小組成員']

df_hasMembers = df[df['小組成員'].str.count(',')>0]
#小組成員不只一人的撈出來跑廻圈處理,以下是廻圈範例:
tmp=[]
for index, row in df_hasMembers.iterrows():
    tmpSN=row['編號']
    tmpGrp=row['組別']
    tmpMember=str(row['小組成員']).split(",")
    for i in tmpMember:
        tmp.append({
            '編號':tmpSN, '組別':tmpGrp,
            '小組成員':row['小組成員'],
            '得獎人員':i,
            '得獎備註':memberWithoutMe(tmpMember,i)
        })
result=new_sample0.append(pd.DataFrame(tmp))
print(result.sort_values(by=['組別','編號']))

我略懂python,對於pandas的了解都是google來的,所以我想肯定是有直接用pandas能處理字串分割重組填充列這些函式,不過因為這部份我了解不夠,就先用自己熟悉的土砲作法:取得每列的值作處理並存入暫存的list,全部處理完後把list轉成pd,總之是完成了。

我要發表回答

立即登入回答