[英]Reshape pandas dataframe by transposing certain columns to rows
我有一個像這樣的熊貓數據框:
+-------+-----+-----------------+----------------+----------------+
| name | age | favourite_color | favourite_food | favourite_city |
+-------+-----+-----------------+----------------+----------------+
| john | 25 | yellow | apple | munich |
| james | 24 | red | onion | melbourne |
+-------+-----+-----------------+----------------+----------------+
我想讓它看起來像這樣:
+-------+-----+--------------------+-----------------------------+
| name | age | favourite category | value of favourite category |
+-------+-----+--------------------+-----------------------------+
| john | 25 | color | yellow |
| john | 25 | food | apple |
| john | 25 | city | munich |
| james | 24 | color | red |
| james | 24 | food | onion |
| james | 24 | city | melbourne |
+-------+-----+--------------------+-----------------------------+
我想采用 3 個“最喜歡的東西”類別並將它們從 3 列分解為 2 列。 一列應該是事物的名稱,另一列應該是事物的價值。
在這個過程中,表中的行數應該乘以 favourite_something 類別的數量(在本例中為 3x),並且諸如 name 和 age 之類的常見值應該被復制。
概括地說,我的數據集每行包含每個人的 3 個觀察值:最喜歡的顏色、食物和城市。 我想重塑數據框,以便在任何給定行中只有一個觀察結果。
請告訴我在數據處理中這個操作是什么,以及在 python 和 pandas 中最簡單的方法。
這本質上是一個可以使用DataFrame.melt
解決的重塑問題。 您的數據框有多個值變量,
new_df = df.melt(id_vars= ['name', 'age'], value_vars=['favourite_color', 'favourite_food', 'favourite_city'], \
var_name='favourite category', value_name='value of favourite category')
new_df['favourite category'] = new_df['favourite category'].replace({'favourite_':''}, regex = True)
name age favourite category value of favourite category
0 john 25 color yellow
1 james 24 color red
2 john 25 food apple
3 james 24 food onion
4 john 25 city munich
5 james 24 city melbourne
由於您希望 reshape('favourite') 的列中有一些共性,可以在此處部署從寬到長的大熊貓:只需說明各種參數,並將其傳遞給函數:
pd.wide_to_long(df,
stubnames ='favourite',
i=['name','age'],
j='favourite category',
suffix = r'(color|food|city)',
sep='_').rename(columns={'favourite':'value of favourite category'}).reset_index()
name age favourite category value of favourite category
0 john 25 color yellow
1 john 25 food apple
2 john 25 city munich
3 james 24 color red
4 james 24 food onion
5 james 24 city melbourne
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.