2 回答

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

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
- 2 回答
- 0 關注
- 170 瀏覽
添加回答
舉報