【问题标题】:CSV Pandas PYTHONCSV Pandas Python
【发布时间】:2015-10-12 20:44:49
【问题描述】:

我有一个如下所示的 CSV 文件

S1,    22,   MD  , 0.022, ,  523.324
S2,    22,   MD  , 4.32,  , 342.54 
S3,    22,   MD  , 3.54,  ,   0.32
S4,    22,   MD  , 4.32,  ,  0.54  
S1,    33,   MD  , 5.32,  ,  0.43
S2,    33,   MD  , 11.54, ,  0.65
S3,    33,   MD  , 22.5,  ,  0.324
S4,    33,   MD  , 45.89  ,  0.32
S1,    44,  MD  , 3.53   ,  3.32
S2,    44,  MD  ,  4.5   ,  0.322
S3,    44,  MD  , 43.65  ,   45.78
S4,    44,   MD,   43.54 , 0.321

该文件没有任何标题,但我不关心 MD

我的输出文件需要如下所示:

 Size ,   S1` ,    S2  ,   S3  ,   S4   

  22   ,  0.022 ,  4.32 ,  45.89 ,  4.32

  33  ,  5.32,    11.54 ,  22.5,   45.89, 

  44  ,  3.53,    4.5,     43.65,  43.54

        3 values, 3 values, 3,values, 3 values

如您所见,输出文件包含标题。最后一行还表示每列中值的总数。

到目前为止我的代码:

将熊猫导入为 pd

将 numpy 导入为 np

导入 csv

df=pd.read_csv(r'C:\Users\testuser\Desktop\file.csv',usecols=[0,1,2,3,4])

df.columns=pd.MultiIndex.from_tuples(zip(['Names','FileSize','x','y','z'],df.columns)) #add 列标题。 ..(这做的不对)

df_out=df.groupby('Names','FileSize').count().reset_index() #假设打印不同的值

df_out.to_csv('processed_data_out.csv', columns['Names','FileSize','x','y','z'], header=False,index=False)

我没有使用输出中的最后一列,因为如果用户要求查看该信息,则应该生成该列。我又遇到了麻烦。

【问题讨论】:

标签: python python-2.7 parsing csv numpy


【解决方案1】:

Pandas 方法非常适合这个。

读取数据:

import pandas as pd

df = pd.read_csv('data_in.csv', names=['Label','Requirements'], skiprows=1) # This assumes and skips the header row ('TSD' in your question)

>>> df
   Label  Requirements
0      A             1
1      A             2
2      A             3
3      A             4
4      A             5
5      B            11
6      B            22
7      B            45
8      C           NaN
9      C           NaN
10     C           NaN

计数要求:

df_out = df.groupby('Label').count().reset_index()

>>> df_out
  Label  Requirements
0     A             5
1     B             3
2     C             0

根据您的需要格式化:

df_out['Output'] = df_out.apply(lambda row: '%s doesn\'t have any requirement'%(row['Label']) if row['Requirements']==0 else '%s has %d requirements'%(row['Label'],row['Requirements']), axis=1)

>>> df_out
  Label  Requirements                          Output
0     A             5            A has 5 requirements
1     B             3            B has 3 requirements
2     C             0  C doesn't have any requirement

导出为 CSV:

df_out.to_csv('processed_data_out.csv', columns=['Output'], header=False, index=False)

【讨论】:

  • 如何解析 pandas 中的 csv。
  • pd.read_csv(...) 部分将为您读取 csv。根据您编辑的问题,由于您的文件没有任何标题并且列是脚本、TSD、要求,您将使用以下内容:names=['Script','TSD','Requirement']。如果第一行确实有标题行,则可以删除 skiprows=1 部分。我的答案中的其余功能将相同。
【解决方案2】:

我建议使用字典:

my_dict = {}
with open(your_file, 'r') as infile:
    for line in infile:
        line_list = line.split(' ')
        if len(line_list) == 2:
            key, requirement = line_list
            if key in my_dict:
                my_dict[key] += 1
            else:
                my_dict[key] = 0
        elif len(line_list) == 1:
            key = line_list[0]
            if key not in my_dict:
                my_dict[key] = 0

然后将字典my_dict写入另一个csv文件...

编辑:这是假设您有一个以空格分隔的文件,但您可以通过任何分隔符更改 line.split(' ') 中的分隔符...

【讨论】:

    猜你喜欢
    • 2016-03-12
    • 1970-01-01
    • 2019-05-19
    • 2016-07-02
    • 1970-01-01
    • 2014-02-07
    • 2018-01-09
    • 2017-06-04
    • 1970-01-01
    相关资源
    最近更新 更多