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.,%.6ffor 6 decimals) to match your data’s needs. - Integer Frequencies: Using
fmt='%d'forfreqsensures 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
相关产品推荐
相关产品推荐

