Pandas技术实现:将横向多产品账户数据转置为纵向格式并重复账户关联信息
Reshape Pandas DataFrame for Salesforce Upload (Wide to Long Format)
This is a classic wide-to-long data reshaping task, and pandas has a built-in function melt() that makes this super straightforward. Here's how to transform your data into the exact format you need for Salesforce:
Step-by-Step Breakdown
- Set Up Pandas: First, ensure pandas is installed and imported.
- Replicate Your Input: Let's start by building the sample DataFrame from your provided input.
- Melt the Wide Data: Use
pd.melt()to pivot all product columns into a singleProductcolumn, keeping the account fields as fixed identifiers. - Clean Up Empty Entries: Drop any rows where the
Productvalue is blank (since those accounts don't own that product). - Reset the Index: Adjust the index to match your expected sequential output.
Full Code Implementation
import pandas as pd # Create the original wide-format DataFrame data = { 'Account Name': ['csld solutions', 'global dynamics', 'running inc.'], 'Acct ID': ['1234', '0256', '2564'], 'crest': ['', 'crest', ''], 'ptx': ['ptx', '', ''], 'gtchange': ['', 'gtchange', 'gtchange'], 'gtfire': ['gtfire', '', 'gtfire'], 'dfdata': ['', 'dfdata', ''] } df = pd.DataFrame(data) # Reshape to long format using melt() melted_df = pd.melt( df, id_vars=['Account Name', 'Acct ID'], # Columns to retain as identifiers value_vars=['crest', 'ptx', 'gtchange', 'gtfire', 'dfdata'], # Product columns to pivot value_name='Product' # Name for the new consolidated product column ) # Remove rows with empty product values and reset index final_df = melted_df[melted_df['Product'] != ''].reset_index(drop=True) print(final_df)
Resulting Output
Account Name Acct ID Product 0 csld solutions 1234 ptx 1 csld solutions 1234 gtfire 2 global dynamics 0256 crest 3 global dynamics 0256 gtchange 4 global dynamics 0256 dfdata 5 running inc. 2564 gtchange 6 running inc. 2564 gtfire
This output matches exactly the structure you need—each product gets its own row paired with the full account details, ready for upload to Salesforce.
内容的提问来源于stack exchange,提问作者mtm1186
相关产品推荐
相关产品推荐

