I was spending hours trying to do such a simple thing, I have a dataframe:
a b c d
0 1 2 3 4
1 5 6 7 8
2 2 3 4 5
3 5 6 7 8
4 1 2 3 4
I have a dictionary:
dic = {'b':6,'d':2}
I would like to do 2 different things :
- Simply add a row to the df, with this
dic
using NaN for column 'a' and 'c' - Modify a row with a condition
a=3
, with this dictionary. For this I tried :
df.loc[df['date'] == date, dic.keys()] = dic.values()
Which provide strange results, like values inside a ()
CodePudding user response:
For new row with default RangeIndex
use DataFrame.loc
:
dic = {'b':6,'d':2}
df.loc[len(df)] = dic
For modify columns by condition working well for me with your solution, for oldier pandas/python version convert keys
and values
to lists:
dic = {'b':60,'d':20}
df.loc[df['a'] == 1, list(dic.keys())] = list(dic.values())
print (df)
a b c d
0 1.0 60 3.0 20
1 5.0 6 7.0 8
2 2.0 3 4.0 5
3 5.0 6 7.0 8
4 1.0 60 3.0 20
5 NaN 6 NaN 2
EDIT:
dic = {'b':60,'d':20}
val = 10
m = df['a'] == val
if m.any():
df.loc[m, list(dic.keys())] = list(dic.values())
else:
df.loc[len(df)] = {**dic, **{'a':val}}
print (df)
a b c d
0 1 2 3.0 4
1 5 6 7.0 8
2 2 3 4.0 5
3 5 6 7.0 8
4 1 2 3.0 4
5 10 60 NaN 20