Reputation: 175
I have a pandas dataframe with a column of integer values but I can't seem to figure out how to put those values within the column into a list.
So for example,
NUMBERS ------> NUMBERS
1 [1]
2 [2]
3 [3]
4 [4]
5 [5]
6 NaN
7 [7]
8 NaN
Thank you.
Upvotes: 1
Views: 3695
Reputation: 164673
This is one way.
df['NUMBERS'] = df['NUMBERS'].apply(lambda x: [x])
However, this is discouraged unless you have a very specific reason, since you lose the vectorisation benefits of pandas
.
To control behaviour when your value is np.nan
:
df = pd.DataFrame({'NUMBERS': list(range(1, 8))})
df['NUMBERS'] = df['NUMBERS'].apply(lambda x: [int(x)] if not pd.isnull(x) \
in (6, 8) else np.nan)
Upvotes: 4
Reputation:
You could also do:
df["NUMBERS"].values.reshape(5,1)
, that would give you
array([[1],
[2],
[3],
[4],
[5]])
which would be an array, which would keep the vectorisation benefit of pandas
.
Or to get a list of lists, you could do:
[[x] for x in df["NUMBERS"]]
which would give:
[[1], [2], [3], [4], [5]]
As @piRSquared suggested, you could do:
df.assign(Numbers=df.Numbers.values.reshape(-1, 1).tolist())
Which would return another DF with each value as a list:
Numbers
0 [1]
1 [2]
2 [3]
3 [4]
4 [5]
Upvotes: 1
Reputation: 323236
numpy
solution
df['Num']=df.NUMBERS.values[:,None].tolist()
df
Out[322]:
NUMBERS Num
0 1 [1]
1 2 [2]
2 3 [3]
3 4 [4]
4 5 [5]
Upvotes: 4