I'm assigning value to column based on index value and if value exists then append the new value to old value
I have tried applying value to column based on index but couldn't append value to already existing value in column
Dataframe:-
foo bar
0 1 1
1 2 2
2 3 3
3 3 3
Code :-
values = ['a', 'b']
for val in values:
df.loc[df['foo'] == 1, foo2] = val
Outupt Dataframe:
foo bar foo2
0 1 1 b
1 2 2
2 3 3
3 3 3
Expected DataFrame:-
foo bar foo2
0 1 1 a,b
1 2 2
2 3 3
3 3 3
As you noticed the line
df.loc[df['foo'] == 1, foo2] = b
overwrites previous value so that you end up with only b
. Is there a particular reason you need to solve your problem this way? You can write a custom function and use apply to append values but this is not how pandas is supposed to be used. I would recommend creating another column 'foo3'
. You can always join the letters afterwards.
This should achieve what you are looking for. However, just as maow already pointed out, you should think about adding new columns and concatenating them when you need to.
import pandas as pd
df = pd.DataFrame({'foo': [1,2,3,3], 'bar': [1,2,3,3], 'foo2':[None, None, None, None]})
print(df)
a = 'a'
b = 'b'
# insert a
df.loc[df['foo'] == 1, 'foo2'] = a
print(df)
# concat b to a
df.loc[df['foo'] == 1, 'foo2'] += ',' + b
print(df)
This should solve your problem
import pandas as pd
df = pd.DataFrame({'foo': [1,2,3,3], 'bar': [1,2,3,3], 'foo2':[None, None, None, None]})
print(df)
print(df)
values = ['a', 'b']
for val in values:
print(df.loc[df['foo'] == 1,'foo2'][0])
if (df.loc[df['foo'] == 1,'foo2'][0]==None):
df.loc[df['foo'] == 1, 'foo2']=val
else:
df.loc[df['foo'] == 1, 'foo2']=df.loc[df['foo'] == 1:,'foo2'] + ',' +val
print(df)
output:
foo bar foo2
0 1 1 a,b
1 2 2
2 3 3
3 3 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.