Python - 合并 CSV 文件中的列

标签 python pandas rows

我正在尝试创建代码,从 CSV 文件中的某些列获取数据并将它们合并到一个新的 CSV 文件中。我被指示使用 Pandas,但我不确定我是否走在正确的轨道上。我对 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

最佳答案

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

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')

关于Python - 合并 CSV 文件中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22122529/

相关文章:

python - 插入mysql数据库,pymysql无法插入

python - 将 pandas 数据框导出为 CSV

python - 阅读 Python 文档对初学者学习 Python 好吗?

python - 如何根据两个字符串列的差异在 pandas 中创建一个新列?

javascript - 如何使用 JavaScript 获取 <textarea> 中的行数?

css - 具有 CSS 网格布局的网格项内元素的高度相等

c# - 如何从二维数组中获取一维列数组和一维行数组? (C#.NET)

Python Beautifulsoup CSS 选择器不起作用

Python Pandas 频率文档

python-3.x - Python find.line 不从文本文件中过滤日期字符串