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

时间:2018-10-24 23:36:16

标签: python python-3.x csv

我有一个如下所示的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库,但没有成功。有没有简单的方法可以做到这一点?

4 个答案:

答案 0 :(得分:1)

您可以将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)])

答案 1 :(得分:0)

您可以尝试熊猫。如果您没有安装熊猫,请执行err1 + err2 + err3 + err4 + result来安装熊猫。

pip install pandas

希望这会有所帮助!

答案 2 :(得分:0)

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

         <!-- Base application theme. -->
        <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
            <!-- Customize your theme here. -->
            <item name="colorPrimaryDark">@color/color_primary</item>
            <item name="colorAccent">@color/color_accent</item>
            <item name="android:textColor">@color/white</item>
            <item name="searchViewStyle">@style/SearchViewStyle</item>
            <!--SearchView query text color-->
            <item name="android:textColorPrimary">@color/textColorPrimary</item>
            <!--SearchView query hint text color-->
            <item name="android:textColorHint">@color/textColorHint</item>
        </style>
        <!--SearchViewStyle -->
        <style name="SearchViewStyle" parent="Widget.AppCompat.SearchView">
            <item name="searchIcon">@drawable/ic_search</item>
            <item name="voiceIcon">@drawable/ic_search_voice</item>
            <item name="closeIcon">@drawable/ic_search_close</item>
            <item name="searchHintIcon">@drawable/ic_search</item>
        </style>

答案 3 :(得分: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

参考

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