![](/img/trans.png)
[英]how to create new columns in pandas based on a column's values within a dataframe (pivot or unpivot ? )
[英]pivot one column in pandas dataframe and create 4 new columns
我正在使用 pandas dataframe。我有這樣的數據:
df
COUNTRY LINE PRODUCT SERVICE
Argelia 1 1.0 Mobile
Argelia 1 2.0 Mobile
Argelia 1 3.0 Mobile
Argelia 2 1.0 Mobile
Argelia 3 2.0 Mobile
Argelia 3 3.0 Mobile
我想按 LINE 和 pivot PRODUCT 列分組,但我需要 4 個產品列(product_1、product_2、product_3 和 product_4),它不關心是否有任何 PRODUCT 值 = 4。
我正在嘗試將get_dummies
與此代碼一起使用:
df = pd.concat([df, pd.get_dummies(dfs['PRODUCT'], prefix='product')], axis=1)
df.drop(['PRODUCT'], axis=1, inplace=True)
df = df.groupby(['COUNTRY', 'LINE', 'SERVICE']).agg({'product_1' : np.max, 'product_2': np.max, 'product_3':np.max, 'product_4':np.max}).reset_index()
但它只給我 3 列產品,我想要 4 列有這個 dataframe:
COUNTRY LINE SERVICE product_1 product_2 product_3 product_4
Argelia 1 Mobile 1 1 1 0
Argelia 2 Mobile 1 0 0 0
Argelia 3 Mobile 0 1 1 0
可能嗎?
(我也需要將 PRODUCT 值類型 1.0 更改為 1)
通過新列使用DataFrame.reindex
和所有可能的產品,這里是替代解決方案,我希望更快地使用DataFrame.pivot_table
, DataFrame.clip
最大1
值, rename
以將浮點列轉換為整數, DataFrame.add_prefix
和reindex
:
cols = [f'product_{i}' for i in range(1, 5)]
df1 = (df.pivot_table(index=['COUNTRY', 'LINE', 'SERVICE'],
columns='PRODUCT',
fill_value=0,
aggfunc='size')
.clip(upper=1)
.rename(columns=int)
.add_prefix('product_')
.reindex(cols, axis=1, fill_value=0))
print (df1)
PRODUCT product_1 product_2 product_3 product_4
COUNTRY LINE SERVICE
Argelia 1 Mobile 1 1 1 0
2 Mobile 1 0 0 0
3 Mobile 0 1 1 0
在您的解決方案中,使用DataFrame.pop
提取列,轉換為整數,然后按max
聚合並添加reindex
:
df = pd.concat([df, pd.get_dummies(df.pop('PRODUCT').astype(int),prefix='product')], axis=1)
cols = [f'product_{i}' for i in range(1, 5)]
df = df.groupby(['COUNTRY', 'LINE', 'SERVICE']).max().reindex(cols, axis=1, fill_value=0)
print (df)
product_1 product_2 product_3 product_4
COUNTRY LINE SERVICE
Argelia 1 Mobile 1 1 1 0
2 Mobile 1 0 0 0
3 Mobile 0 1 1 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.