【问题标题】:How to get the average length of the strings in each column in csv?如何获取csv中每列字符串的平均长度?
【发布时间】:2019-03-29 11:29:51
【问题描述】:

我有一个如下所示的 csv:

someFile.csv

Header1 Header2 Header3
aa      aaa     a
bbbb    bbbbbb  aa

我想计算每列的平均字符串长度并创建结果的 csv。这就是示例中的样子:

results.csv

Header1 Header2 Header3
3       4.5     1.5

我一直在尝试在 Python 中使用 csv 库,但没有成功。有没有一种简单的方法可以做到这一点?

【问题讨论】:

  • 你的尝试是什么?显示一些代码,以便我们可以有知识地发表评论。

标签: python python-3.x csv


【解决方案1】:

你可以试试熊猫。如果您没有安装 pandas,请通过pip install pandas 安装 pandas。

import pandas as pd
# df = pd.read_csv('my_csv.csv')
df = pd.DataFrame([['aa', 'aaa', 'a'], ['bbbb', 'bbbbbb', 'aa']], 
                  columns=['Header1', 'Header2', 'Header3'])
result = pd.DataFrame([[]])
for col in df:
    result[col] = df[col].apply(len).mean()

result.to_csv('result.csv')

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    您可以zip 行和map 列到len 并使用statistics.mean 计算平均值:

    import csv
    from statistics import mean
    with open('someFile.csv', 'r', newline='') as f, open('results.csv', 'w', newline='') as output:
        reader = csv.reader(f, delimiter=' ', skipinitialspace=True)
        headers = next(reader)
        writer = csv.writer(output, delimiter = ' ')
        writer.writerow(headers)
        writer.writerow([mean(map(len, col)) for col in zip(*reader)])
    

    【讨论】:

    • 确实如此。然后按照建议进行编辑。谢谢。
    • 糟糕。确实是匆忙搞混了。谢谢。
    【解决方案3】:

    这是一个简单的代码。我提供了两个块,如果数据帧中没有空值并且存在空值。

    import pandas as pd
    
    #df = pd.DataFrame([['aa','aaa','a'],['bbbb','bbbbbb','aa']],columns=['Header1','Header2','Header3'])
    df = pd.read_csv('file.csv')
    
    #if No Null
    No_of_Row=df.shape[0]
    for Col in df.sum():
        print(len(Col)/No_of_Row)
    
    #if Null are there
    for Col,Header in zip(df.sum(),df.columns):
        print(len(Col)/df[[Header]].dropna().shape[0])
    

    【讨论】:

      【解决方案4】:

      这不是最好的方法。还有其他方法可以快速做到这一点。但是,我确实认为这是一个相当直接且易于理解的示例,并且非常仓促地组合在一起。我在你的例子中使用了这个,它有效。

      import csv
      
      # replace "yourusername" with your PC user name
      input_file = 'C:/Users/yourusername/Desktop/someFile.csv' 
      output_file = 'C:/Users/yourusername/Desktop/output.csv'
      
      csv_file = open(input_file, newline='')  # opening csv file
      info = list(csv.reader(csv_file))  # convert data in csv file to array/list
      csv_file.close()
      
      length = len(info[0])  # if you ever add more headers, this will account for it
      avg_container = [0 for i in range(length)]  # creates empty array with zeros for each header
      n = len(info[1:])  # for dividing by n to get average
      
      # adding the lengths of all the items to one sum for each "column"
      for k in info[1:]:
          for n,i in enumerate(k):
              avg_container[n] += len(i)
      
      # diviving all sums by n
      for i in range(len(avg_container)):
          avg_container[i] = avg_container[i]/n
      
      # combine header and average array into one item to write to csv
      avg_output = []
      avg_output.extend((info[0],avg_container))
      print(avg_output)  # just for you to see for yourself
      
      # outputting the new file
      output_csv = open(output_file, 'w', newline='')  # creates an instance of the file
      csv_writer = csv.writer(output_csv)  # creates an "Writer" to write to the csv
      csv_writer.writerows(avg_output)  # outputs the avg_output variable to the csv file
      output_csv.close()  # finished
      

      参考文献

      How to import a csv-file into a data array?

      Create a .csv file with values from a Python list

      Writing a Python list of lists to a csv file

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-20
        相关资源
        最近更新 更多