How to store numpy elements in pandas
1. Problem description
There was a problem with saving NUMpy as an element in pandas, not as a list of elements. But in the process of practice, it was not smooth, and mistakes would be reported. Now I have solved this problem, and share my experience and understanding, hoping to help the future people.
2. Development
1. Create some pseudo data for saving
import pandas as pd
import numpy as np
l1 = [1.2.3.4]
l2 = [1..2..3..4.]
lists = np.array([l1,l2])
labels = [1.0]
Copy the code
2. Create a DataFrame to save and display
df = pd.DataFrame()
df["list"] = lists
df["label"] = labels
print(df)
Copy the code
This program error:
raise Exception('Data must be 1-dimensional')
Exception: Data must be 1-dimensional
Copy the code
Error df[“list”] = lists, lists are not one-dimensional Data (Data must be 1-dimensional)
The reason is lists = np.array([l1,l2]), lists become two-dimensional np.array, shape is (2,4).
How to solve it? We need to convert Np. array to list to make it one-dimensional
Fix the code
import pandas as pd
import numpy as np
l1 = [1.2.3.4]
l2 = [1..2..3..4.]
lists = np.array([l1,l2])
lists = list(lists)
labels = [1.0]
df = pd.DataFrame()
df["list"] = lists
df["label"] = labels
print(df)
Copy the code
Output result:
List label 0 [1.0, 2.0, 3.0, 4.0] 1 1 0 [0.1, 0.2, 0.3, 0.4]Copy the code
Array ([L1, L2]) is converted to Np. array and then converted to list(lists). In fact, this is to simulate the real use of the scene. If the text is stored in pandas, the error must be 1-dimensional. If the text is stored in pandas, the error must be 1-dimensional.
What’s the difference between numpy.array and list? I’ll explain it in a blog post.