'Writting columns of data in *.dat file in Python

I want to write specific data, say, after analysis I get in the following fashion shown in the above figure so that whenever requires I can extract any particular column as I wish following the commands:
f= np.loadtxt("Data1.dat", unpack=True)
x = f[0,:]
However, I have tried pd.DataFrame() but didn't work.
import csv
import numpy as np
import pandas as pd
x = [0.11, 2.15, 0.39, 5.79, 6.53]
y = [99.2, -0.32, -12.95, -2.5, -7.5]
n = len(x)
#with open('data1.dat', 'w', newline='') as f:
# wtr = csv.writer(f)
# for k in range(n):
# wtr.writerow([x[k], y[k]])
df = pd.DataFrame({"x": x, "y": y})
df.to_csv('data1.dat')
Solution 1:[1]
You can use column_stack from numpy:
import numpy as np
x = [0.11, 2.15, 0.39, 5.79, 6.53]
y = [99.2, -0.32, -12.95, -2.5, -7.5]
df = np.column_stack((x,y))
np.savetxt('data1.dat', df, header = ' x, y ')
Later, your data should look like you want. Then it's easy to read with:
data = np.loadtxt('data1.dat', unpack=True)
x = data[0]
y = data[1]
Good luck!
Solution 2:[2]
$project can be used to get required values.
Example:
bson.M {
"$project": bson.M {
"A": "$_id.A",
"B": "$_id.B",
"Total": 1
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Someone_with_time |
| Solution 2 | Tyler2P |
