python-3.x - Distribute the values of one column into N columns
问题描述
I have one column contain (1968) integer values (rows) how can separate these values into for example 5 columns? Data in the column(inside csv file) something like this:
34
33
28
22
21
19
18
25
15
5
0
-8
-10
-19
-25
-39
-49
I need the output be in csv file and like this(The data is distributed on the required columns)
22 18 5 -10
21 25 0 -19
19 15 -8 -25
-39
-49
解决方案
You can partition your data with np.array_split
like so:
n_columns = 4 # Number of columns you want
data = [34, 33, 28, 22, 21, 19, 18, 25, 15, 5, 0, -8, -10, -19, -25, -39, -49]
data = np.array(data) # You already have your data
columns = np.array_split(data, n_columns, axis=0)
Then build a dataframe with columns
and export it to a csv
file with to_csv
using sep=';'
so that different columns are used inside your file, instead of entries being separated with a ,
.
df = pd.DataFrame(columns).T
df.to_csv("data.csv", sep=';', index=False, header=False)