亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將列表中包含值的列轉換為按特定列分組的分隔行

將列表中包含值的列轉換為按特定列分組的分隔行

PHP
翻翻過去那場雪 2023-11-09 10:36:42
我正在嘗試將列表中包含值的列轉換為按特定列分組的分隔行。這就是我的數據框:id        rooms        bathrooms        facilities             111       1            2                [2, 3, 4]222       2            3                [4, 5, 6]333       2            1                [2, 3, 4]這就是我需要的數據框:id        rooms        bathrooms        facility             111       1            2                2111       1            2                3111       1            2                4222       2            3                4222       2            3                5222       2            3                6333       2            1                2333       2            1                3333       2            1                4我試圖首先轉換為列出列設施:facilities = pd.DataFrame(df.facilities.tolist())然后按列連接并按照相同的方法使用另一個建議的解決方案:df[['id', 'rooms', 'bathrooms']].join(facilities).melt(id_vars=['id', 'rooms', 'bathrooms']).drop('variable', 1)不幸的是,它對我不起作用。另一個解決方案?
查看完整描述

2 回答

?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

你需要explode

df.explode('facilities')


#? ? id? rooms? bathrooms facilities

#0? 111? ? ? 1? ? ? ? ? 2? ? ? ? ? 2

#0? 111? ? ? 1? ? ? ? ? 2? ? ? ? ? 3

#0? 111? ? ? 1? ? ? ? ? 2? ? ? ? ? 4

#1? 222? ? ? 2? ? ? ? ? 3? ? ? ? ? 4

#1? 222? ? ? 2? ? ? ? ? 3? ? ? ? ? 5

#1? 222? ? ? 2? ? ? ? ? 3? ? ? ? ? 6

#2? 333? ? ? 2? ? ? ? ? 1? ? ? ? ? 2

#2? 333? ? ? 2? ? ? ? ? 1? ? ? ? ? 3

#2? 333? ? ? 2? ? ? ? ? 1? ? ? ? ? 4


查看完整回答
反對 回復 2023-11-09
?
慕容森

TA貢獻1853條經驗 獲得超18個贊

將列表作為數據框中的值有點尷尬,因此我能想到的解決此問題的一種方法是解壓列表并將每個列表存儲在其自己的列中,然后使用熔化函數。


# recreate your data

d = {"id":[111, 222, 333],

    "rooms": [1,2,2],

    "bathrooms": [2,3,1],

    "facilities": [[2, 3, 4],[4, 5, 6],[2, 3, 4]]}


df = pd.DataFrame(d)


# unpack the lists

f0, f1, f2 = [],[],[]


for row in df.itertuples():

    f0.append(row.facilities[0])

    f1.append(row.facilities[1])

    f2.append(row.facilities[2])

    

df["f0"] = f0

df["f1"] = f1

df["f2"] = f2


# melt the dataframe

df = pd.melt(df, id_vars=['id', 'rooms', 'bathrooms'], value_vars=["f0", "f1", "f2"], value_name="facilities")


# optionally sort the values and remove the "variable" column

df.sort_values(by=['id'], inplace=True)

df = df[['id', 'rooms', 'bathrooms', 'facilities']]

我認為這應該可以為您提供所需的數據框。


    id  rooms   bathrooms   facilities

0   111 1   2   2

3   111 1   2   3

6   111 1   2   4

1   222 2   3   4

4   222 2   3   5

7   222 2   3   6

2   333 2   1   2

5   333 2   1   3

8   333 2   1   4


查看完整回答
反對 回復 2023-11-09
  • 2 回答
  • 0 關注
  • 170 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號