如何在 CSV 中获取每列字符串的平均长度?

6
我有一个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库,但是没有成功。有没有简单的方法来完成这个任务?


1
你有什么尝试吗?请展示一些代码,这样我们才能够有针对性地进行评论。 - ncmathsadist
4个回答

16
你可以尝试使用 pandas。如果你没有安装 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
你可以将行压缩并将列映射到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)])

确实。按建议进行了编辑。谢谢。 - blhsing
糟糕,确实匆忙中搞混了。谢谢。 - blhsing

0
这是一个简单的代码。我提供了两个块,一个用于处理数据框中没有空值的情况,另一个用于处理存在空值的情况。
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])

0

这不是最好的方法。有其他更快的方法来完成这个任务。然而,我认为这是一个相当简单易懂的例子,是匆忙拼凑出来的。我在你的示例上使用了它,它可以工作。

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

参考资料

如何将CSV文件导入数据数组?

使用Python列表中的值创建CSV文件

将Python列表中的列表写入CSV文件


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接