1

I have a dataset where I would like to append rows if this value is missing from a specific column.

Data

ID  Date    type    energy
AA  Q1 2022 a       1
AA  Q2 2022 ok      1
AA  Q3 2022 yes     1
AA  Q4 2022 yes     4
FC  Q1 2022 no      4
FC  Q2 2022 no      4
FC  Q3 2022 yes     45
FC  Q4 2022 yes     5
        
        

Desired

ID  Date    type    energy
AA  Q1 2022 a       1
AA  Q2 2022 ok      1
AA  Q3 2022 yes     1
AA  Q4 2022 yes     4
FC  Q1 2022 no      4
FC  Q2 2022 no      4
FC  Q3 2022 yes     45
FC  Q4 2022 yes     5
BC  Q1 2022         0
DA  Q1 2022         0

Doing

#values =   {'BC': 'Q1 2022', 'DA': 'Q1 2022}
#df1 = df.merge(df, how='left').fillna({'energy': 0})

However, this is not appending, not sure how to attach the values dictionary within this script. I am still researching, any assistance is appreciated.

4 Answers 4

1

We could do

apdf = pd.Series(values).reset_index()
apdf.columns = df.columns[:2]
df = pd.concat([df, apdf]).fillna({'energy': 0})
Sign up to request clarification or add additional context in comments.

Comments

1

You can try with a dict-comprehension and append. In a one-liner:

df = df.append(pd.DataFrame({'ID':[x for x in values],
                        'Date':[values[x] for x in values]}))

1 Comment

append? deprecated...
0

Python expects a list for the values of the dictionary rather than values. Then, use append()

df1 = pd.DataFrame({'BC': ['Q1 2022'], 'DA': ['Q1 2022']})
df = df.append(df1)

# replace to satisfy the desired output
df['energy'].fillna(0, inplace=True)
df['type'].fillna('', inplace=True)

2 Comments

Not a fan of manually inputting the data for the DataFrame function
agreed but I think this answer makes it clear how to go about creating a df from a dict which I think might be where the OP was stuck
0
values = {'BC': 'Q1 2022', 'DA': 'Q1 2022'}
df = pd.concat([df, pd.DataFrame({
    "Date": values.values(),
    "type": "",
    "energy": 0,
    }, index=values.keys())])

Comments

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.