Blank
Blank

Reputation: 175

Convert integers in a dataframe column to a list

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

Answers (3)

jpp
jpp

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

user6530460
user6530460

Reputation:

You could also do:

Array

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.

List of Lists

Or to get a list of lists, you could do:

[[x] for x in df["NUMBERS"]]

which would give: [[1], [2], [3], [4], [5]]

DF of Lists

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

BENY
BENY

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

Related Questions