5

I have the pandas.DataFrame below:

enter image description here

One of the columns from the Dataframe, pontos, holds a dict for each of the rows.

What I want to do is add one column to the DataFrame for each key from this dict. So the new columns would be, in this example: rodada, mes, etc, and for each row, these columns would be populated with the respective value from the dict.

So far I've tried the following for one of the keys:

df_times["rodada"] = [df_times["pontos"].get('rodada') for d in df_times["pontos"]]

However, as a result I'm getting a new column rodada filled with None values:

enter image description here

Any hints on what I'm doing wrong?

3 Answers 3

6

You can create a new dataframe and concat it to the current one like:

Code:

df2 = pd.concat([df, pd.DataFrame(list(df.pontos))], axis=1)

Test Code:

import pandas as pd

df = pd.DataFrame([
    ['A', dict(col1='1', col2='2')],
    ['B', dict(col1='3', col2='4')],
], columns=['X', 'D'])

print(df)

df2 = pd.concat([df, pd.DataFrame(list(df.D))], axis=1)
print(df2)

Results:

   X                           D
0  A  {'col2': '2', 'col1': '1'}
1  B  {'col2': '4', 'col1': '3'}

   X                           D col1 col2
0  A  {'col2': '2', 'col1': '1'}    1    2
1  B  {'col2': '4', 'col1': '3'}    3    4
Sign up to request clarification or add additional context in comments.

Comments

2

You just need a slight change in your comprehension to extract that data.

It should be:

df_times["rodada"] = [d.get('rodada') for d in df_times["pontos"]]

You want the values of the dictionary key 'rodada' to be the basis of your new column. So you iterate over those dictionary entries in the loop- in other words, d, and then extract the value by key to make the new column.

Comments

0

you can also use join and pandas apply function:

df=df.join(df['pontos'].apply(pd.Series))

1 Comment

Code only answers are discouraged. Please add some explanation as to how this solves the problem, or how this differs from the existing answers. From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.