You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python技术咨询:如何将频次统计结果分存为两个单列文本文件

Save Unique Values & Frequencies as Separate Single-Column Text Files

Hey there! You’ve already nailed the core steps—sorting your dataset and computing unique values with their frequencies. To save items and freqs into separate single-column text files, here’s how to extend your existing code:

Updated Code with Saving Functionality

import numpy as np

K = [0.11729534, 0.16569225, 0.2672644, 0.19168988, 0.095590018, 0.082994543, 0.087023214, 0.10699161, 0.063435465, 0.028770683, 0.029708872, 0.041429114, 0.046457175, 0.057534702, 0.045394801, 0.051440958, 0.05362796, 0.072624497, 0.099292949, 0.22106786, 0.30126628] # K values in descending order
K_sorted = sorted(K, reverse=True)
# Calculate frequency for the K values in descending order
items, freqs = np.unique(K_sorted, return_counts=True)
items, freqs = items[::-1], freqs[::-1]
print('New K list without repetitions= ',items)
print('Frequency= ',freqs)

# Save unique values to a single-column text file
np.savetxt('unique_values.txt', items, fmt='%.8f')  # Adjust decimal precision as needed

# Save frequencies to a single-column text file
np.savetxt('frequencies.txt', freqs, fmt='%d')  # %d ensures integer frequencies are saved correctly

Key Details:

  • np.savetxt(): This NumPy function simplifies writing arrays to text files in clean, columnar format.
  • Decimal Precision: For items, fmt='%.8f' outputs 8 decimal places—tweak the number (e.g., %.6f for 6 decimals) to match your data’s needs.
  • Integer Frequencies: Using fmt='%d' for freqs ensures counts are saved as whole numbers, no unnecessary decimals.

Alternative: Pure Python (No NumPy for Saving)

If you’d rather use built-in Python tools without NumPy for the saving step, try this:

# Save unique values
with open('unique_values.txt', 'w') as f:
    for item in items:
        f.write(f"{item:.8f}\n")

# Save frequencies
with open('frequencies.txt', 'w') as f:
    for freq in freqs:
        f.write(f"{freq}\n")

This loops through each element and writes it on a new line, with the same precision control for numerical values.

内容的提问来源于stack exchange,提问作者sa2233

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 07:17:55