Home > other >  Insert a list of containing one element into a pandas dataframe cell
Insert a list of containing one element into a pandas dataframe cell

Time:09-02

I am trying to insert a list that only contains a single element into a cell in a dataframe.

The table currently looks like this:

| Power | Duration |
|-------|----------|
| 73    |   [0]    |
| 3     |   [0]    | 

I created the table using this code:

df=pd.DataFrame(columns=['Power','Duration'])
df['Power'] = [73, 0]
df['Duration'] = [[0]] * 2

I would like to get the following:

| Power | Duration |
|-------|----------|
| 73    |   [1]    |
| 3     |   [0]    | 

I have tried using

df.loc[df['Power']==73, 'Duration'] = [1]
df.loc[df['Power']==73, 'Duration'] = [[1]]

but both of those returned

| Power | Duration |
|-------|----------|
| 73    |    1     |
| 3     |   [0]    | 

Using

df.loc[df['Power']==73, 'Duration'] = [[[1]]]

returned

| Power | Duration |
|-------|----------|
| 73    |  [[1]]   |
| 3     |   [0]    | 

I also tried

df.loc[df['Power']==73, 'Duration'].iloc[0] = [1]

but that bit of code did not make any changes to the table.

CodePudding user response:

You may use df.apply to include those elements in a list after you assigned that item:

df.loc[df['Power']==73, 'Duration'] = [1]
df.Duration.apply(lambda x: [x] if type(x) is not list else x)
  • Related