我有一個有60列的資料框架,其中大部分都是關于其他銷售產品的資訊,它看起來是這樣的:
我有一個有60列的資料框架,其中大部分都是關于其他銷售產品的資訊。
store_id|seller_id | produtc_0_code |product_0_value |product_1_code |product_1_value
----------------------------------------------------------------------------------
12 | 1234 | a2356 | 52, 20 | ae822,| 50,20 !
為了減少列的數量,我一直試圖把列中的值放在行中,像這樣:
為了減少列的數量,我一直試圖把列中的值放在行中。
store_id |seller_id | product_ code |product_value
12 | 1234 | a2356 | 52,20 !
12 | 1234 | ae822 | 50,20 !
也就是說,保留store_id和seller_id的值,但從products_code和products_value列中取值并在新行中插入。
uj5u.com熱心網友回復:
pivot_longer來自pyjanitor也可以幫助這個轉換;因為你的列有一個順序(一些以代碼結束,其他以價值結束):
# pip install pyjanitor。
import pandas as pd
import janitor as jn
df.pivot_longer(index = ['store_id'/span>, 'seller_id'/span>]。
names_to = ['product_code', 'product_value']。
names_pattern = ["code$", "value$"])
store_id seller_id product_code product_value
0 12 1234 a2356 52,20.
1 12 1234 ae822, 50,20
也可以使用pd.wide_to_long來重塑。
首先,用str.replace重新排列列的順序:
pat = "(?P<start>. )_(?P<middle>. )_(?P<end>. )"/span>
repl = lambda m : f"{m.group('start'/span>)}_{m. group('end')}_{m.group('middle')}"
df.columns = df.columns.str.replace(pat, repl, regex = True)
# 或者直接跳過上述步驟,使用@HenryEcker的這個選項。
# df.columns = df.columns.str.replace(r'(. )_(. )_(. )', r'1_3_2', regex=True)
應用pd.wide_to_long:
pd.wide_to_long(df,
stubnames = ['product_code'/span>, 'product_value'/span>]。
i = ['store_id', 'seller_id'],
j = 'num',
sep='_').droplevel('num') .reset_index()
store_id seller_id product_code product_value
0 12 1234 a2356 52, 20
1 12 1234 ae822, 50,20
uj5u.com熱心網友回復:
我們可以使用set_index stack,但是我們首先需要使用str.split創建一個多索引:
# Set index to the columns to be unffected
new_df = df.set_index(['store_id', 'seller_id'] )
# 將剩余的列分割成一個多索引。
new_df.columns = new_df.columns.str.split('_', expand=True)
# 堆疊中間層(數字)到行。
new_df = new_df.stack(1).droplevel(-1)
# 將多索引列連接在一起。
new_df.columns = new_df.columns.map('_'/span>.join)
# 重置為默認范圍索引。
new_df = new_df.reset_index()
*注意,這假定其余的列有由_分隔的值,在第二個分割位置有一個數字。
new_df:
store_id seller_id product_code product_value
0 12 1234 a2356 52, 20
1 12 1234 ae822, 50,20
使用的設定:
import pandas as pd
df = pd.DataFrame({
'store_id': [12], 'seller_id': [1234], 'product_0_code'/span>: ['a2356']。
'product_0_value': ['52,20'], 'product_1_code': ['ae822,']。
'product_1_value': ['50,20'].
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/331581.html
標籤:
