从Python中的行信息创建新列

huangapple go评论110阅读模式
英文:

Create new columns from information on rows in Python

问题

以下是要翻译的内容:

  1. 所以我有一个具有以下结构的Pandas数据框
  2. | 客户ID | 产品 | 数量 |
  3. |:---- |:------:| -----:|
  4. | 01 | 苹果 | 2 |
  5. | 01 | 橙子 | 3 |
  6. | 01 | 香蕉 | 1 |
  7. | 02 | 苹果 | 4 |
  8. | 02 | 香蕉 | 2 |
  9. 并且希望将此数据框转换为如下所示
  10. | 客户ID | 产品_苹果 | 数量_苹果 | 产品_橙子 | 数量_橙子 | 产品_香蕉 | 数量_香蕉 |
  11. |:---- |:------:|:------: |:------:|:------:|:------:|-----:|
  12. | 01 | 1 | 2 | 1 | 3 | 1 | 1 |
  13. | 02 | 1 | 4 | 0 | 0 | 1 | 2 |
  14. 其中以产品开头的列是二进制变量
  15. 这个转换的Python代码是什么
英文:

So I have a Pandas dataframe with the following structure:

ClientId Product Quantity
01 Apples 2
01 Oranges 3
01 Bananas 1
02 Apples 4
02 Bananas 2

and would like to get this df to look like:

ClientId Product_Apples Quantity_Apples Product_Oranges Quantity_Oranges Product_Bananas Quantity_Bananas
01 1 2 1 3 1 1
02 1 4 0 0 1 2

where the columns starting with Product are binary variables.

What would be the Python code for this transformation?

答案1

得分: 2

假设您的数据集是一个Pandas数据帧,您可以尝试以下方法:

  1. import pandas as pd
  2. df = pd.DataFrame({
  3. 'ClientID': ['01']*3 + ['02']*2,
  4. 'Product': ['Apples', 'Oranges', 'Bananas', 'Apples', 'Bananas'],
  5. 'Quantity': [2, 3, 1, 4, 2]
  6. })
  7. df['product_cnt'] = 1
  8. # 解决方案 1
  9. df.pivot(index='ClientID', columns='Product', values=['Quantity', 'product_cnt']).fillna(0)
  10. # 解决方案 2
  11. df_products = df.pivot(index='ClientID', columns='Product', values='product_cnt').fillna(0).add_prefix('Product_')
  12. df_qty = df.pivot(index='ClientID', columns='Product', values='Quantity').fillna(0).add_prefix('Quantity_')
  13. df_products.merge(df_qty, on='ClientID', how='left')

这是您提供的代码的翻译部分。

英文:

Assuming your dataset is a pandas dataframe, you can try this:

  1. import pandas as pd
  2. df = pd.DataFrame({
  3. 'ClientID': ['01']*3 + ['02']*2,
  4. 'Product': ['Apples', 'Oranges', 'Bananas', 'Apples', 'Bananas'],
  5. 'Quantity': [2, 3, 1, 4, 2]
  6. })
  7. df['product_cnt'] = 1
  8. # solution 1
  9. df.pivot(index='ClientID', columns='Product', values=['Quantity', 'product_cnt']).fillna(0)
  10. # solution 2
  11. df_products = df.pivot(index='ClientID', columns='Product', values='product_cnt').fillna(0).add_prefix('Product_')
  12. df_qty = df.pivot(index='ClientID', columns='Product', values='Quantity').fillna(0).add_prefix('Quantity_')
  13. df_products.merge(df_qty, on='ClientID', how='left')

huangapple
  • 本文由 发表于 2023年7月10日 17:40:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76652517.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定