Python - 在CSV文件中组合列

时间:2014-03-02 00:56:57

标签: python pandas rows

我正在尝试创建代码,该代码将从CSV文件中的某些列中获取数据,并将它们合并到一个新的CSV文件中。我被指示使用熊猫,但我不确定我是否在正确的轨道上。我对Python很陌生,所以要为可能糟糕的代码做好准备。

我想使用data.csv:

Customer_ID,Date,Time,OtherColumns,A,B,C,Cost
1003,January,2:00,Stuff,1,5,2,519
1003,January,2:00,Stuff,1,3,2,530
1003,January,2:00,Stuff,1,3,2,530
1004,Feb,2:00,Stuff,1,1,0,699

并创建一个如下所示的新CSV:

Customer_ID,ABC
1003,152
1003,132
1003,132
1004,110

到目前为止我所拥有的是:

import csv
import pandas as pd

df = pd.read_csv('test.csv', delimiter = ',')
custID = df.customer_ID
choiceA = df.A
choiceB = df.B
choiceC = df.C

ofile  = open('answer.csv', "wb")
writer = csv.writer(ofile, delimiter = ',')
writer.writerow(custID + choiceA + choiceB + choiceC)

不幸的是,所有这一切都是将每一行添加到一起,然后创建每行汇总为一行的CSV。我真正的最终目标是在A-C列中找到最常出现的值,并使用最多出现的值将每个客户组合到同一行中。我很难解释。我想要一些需要data.csv的东西,然后做到这一点:

Customer_ID,ABC
1003,132
1004,110

1 个答案:

答案 0 :(得分:2)

您可以对感兴趣的列求和(如果它们的类型是字符串):

In [11]: df = pd.read_csv('data.csv', index_col='Customer_ID')

In [12]: df
Out[12]:
                Date  Time OtherColumns  A  B  C  Cost
Customer_ID
1003         January  2:00        Stuff  1  5  2   519
1003         January  2:00        Stuff  1  3  2   530
1003         January  2:00        Stuff  1  3  2   530
1004             Feb  2:00        Stuff  1  1  0   699

In [13]: res = df[list('ABC')].astype(str).sum(1)  # cols = list('ABC')

In [14]: res
Out[14]:
Customer_ID
1003           152
1003           132
1003           132
1004           110
dtype: float64

要获取csv,您可以先使用to_frame(添加所需的列名称):

In [15]: res.to_frame(name='ABC')  # ''.join(cols)
Out[15]:
             ABC
Customer_ID
1003         152
1003         132
1003         132
1004         110

In [16]: res.to_frame(name='ABC').to_csv('new.csv')