我正在尝试将看起来像第一个示例的CSV转换为看起来像下面第二个示例的CSV。
我一直在和Pandas一起玩,并认为我的基础工作正常,但我似乎无法弄明白如何进行最后一次转换(从我在枢轴中的占位符值到实际的英文单词)
在下面的代码中,我需要帮助的部分是注释“我需要弄清楚我可以放在这里的东西,它将替换在列的单元格中找到的任何非空值[c ]使用字符串'registered'。“
注意 - 如果您建议一种更有效的方式来遍历数据而不是列名列表上的for循环,请随意。 for循环只是一种测试功能的方法,因为我第一次使用Pandas。
输入:
First Last Email Program
john doe jd@me.com BasketWeaving
jane doe dj@me.com BasketWeaving
jane doe dj@me.com Acrobatics
jane doe dj@me.com BasketWeaving
mick jag mj@me.com StageDiving
期望的输出:
First Last Email StatusBasketWeaving__c StatusAcrobatics__c StatusStageDiving__c
john doe jd@me.com registered
jane doe dj@me.com registered registered
mick jag mj@me.com registered
(实际上我的代码插入了一列,但是这个例子太宽了,所以这里没有显示。)
这是我到目前为止所写的内容:
import pandas
import numpy
# Read in the First Name, Last Name, Email Address, & "Program Registered For" columns of a log file of registrations conducted that day.
tally = pandas.read_csv('tally.csv', names=['First', 'Last', 'Email', 'Program'])
# Rename the First Name & Last Name columns so that they're Salesforce Contact object field names
tally.rename(columns={'First':'FirstName', 'Last':'LastName'}, inplace=True)
# Create a concatenation of First, Last, & Email that can be used for later Excel-based VLOOKUP-ing Salesforce Contact Ids from a daily export of Id+Calculated_Lastname_Firstname_Email from Salesforce
tally['Calculated_Lastname_Firstname_Email__c'] = tally['LastName'] + tally['FirstName'] + tally['Email']
# Rename the values in Program so that they're ready to become field names for the Salesforce Contact object
tally['Program'] = 'Status' + tally['Program'] + '__c'
# Pivot the data by grouping on First+Last+Email+(Concatenated), listing the old registered-for-Program values as column headings, and putting
# a non-null value under that column heading if the person has any rows indicating that they registered for it.
pivottally = pandas.pivot_table(tally, rows=['FirstName', 'LastName', 'Email', 'Calculated_Lastname_Firstname_Email__c'], cols='Program', aggfunc=numpy.size)
# Grab a list of column names that have to do with the programs themselves (these are where we'll want to replace our non-null placeholder with 'Registered')
statuscolumns = [s for s in (list(pivottally.columns.values)) if s.startswith('Status')]
for c in statuscolumns:
#pivottally.rename(columns={c:'Hi'+c}, inplace=True) # Just a test line to make sure my for loop worked.
# I need to figure out something I can put here that will replace any non-null value found in the cells of column pivottally[c] with the string 'Registered'
print(pivottally.head())
#pivottally.to_csv('pivottally.csv')
感谢您的帮助。