Reputation: 407
Let's assume I have this dataframe df
:
'Location' 'Rec ID' 'Duration'
0 Houston 126 17
1 Chicago 338 19.3
I would like to add a column with arrays corresponding to my recordings like:
'Location' 'Rec ID' 'Duration' 'Rec'
0 Houston 126 17 [0.2, 0.34, 0.45, ..., 0.28]
1 Chicago 338 19.3 [0.12, 0.3, 0.41, ..., 0.39]
When I do the df.set_value()
command I get the following error:
ValueError: setting an array element with a sequence.
Upvotes: 3
Views: 5299
Reputation: 863751
I think the easiest is to assign list
of lists
, only you need same length of lists
as length
of DataFrame
:
arr = [[0.2, 0.34, 0.45, 0.28], [0.12, 0.3, 0.41, 0.39]]
print (arr)
[[0.2, 0.34, 0.45, 0.28], [0.12, 0.3, 0.41, 0.39]]
print (len(arr))
2
print (len(df))
2
df["'Rec'"] = arr
print (df)
'Location' 'Rec ID' 'Duration' 'Rec'
0 0 Houston 126 17.0 [0.2, 0.34, 0.45, 0.28]
1 1 Chicago 338 19.3 [0.12, 0.3, 0.41, 0.39]
If use numpy array
, first convert tolist
:
arr = np.array([[0.2, 0.34, 0.45, 0.28], [0.12, 0.3, 0.41, 0.39]])
print (arr)
[[ 0.2 0.34 0.45 0.28]
[ 0.12 0.3 0.41 0.39]]
df["'Rec'"] = arr.tolist()
print (df)
'Location' 'Rec ID' 'Duration' 'Rec'
0 0 Houston 126 17.0 [0.2, 0.34, 0.45, 0.28]
1 1 Chicago 338 19.3 [0.12, 0.3, 0.41, 0.39]
Upvotes: 1