How to fill missing value based on column comparison Python

Clash Royale CLAN TAG#URR8PPPHow to fill missing value based on column comparison Python
I want to fill the missing values in col 2 to corresponding col1.
import pandas as pd
data={"col1":["A","B","C","A","B","C","A","B","A"], "col2":["hey1"," ","hello2","hey2","he1","hello3"," ","","hey1"]}
df=pd.DataFrame(data=data)
It should fill it with some rules, given below:
for example, if A is occuring four times and out of 4, it has corresponding col2 value for three times and fourth one is missing,
so missing value should be a combination of all three. Like in this case 3 values are hey1, hey2, hey1. Fourth missing
should contain hey2, hey1.
Desired output:
col1 col2
A hey1
B he1
C hello2
A hey2
B he1
C hello3
A hey1,hey2
B he1
A hey1
1 Answer
1
data = {"col1": ["A", "B", "C", "A", "B", "C", "A", "B", "A"],
"col2": ["", " ", "hello2", "hey2", "he1", "hello3", " ", "", ""]}
col1 = data["col1"]
col2 = data["col2"]
d = collections.defaultdict(list)
new_col2 =
for i, tup in enumerate(list(zip(col1, col2))):
key, value = tup
if not value.strip():
new_val = ", ".join(d[key])
if not new_val:
if len(new_col2) >= 1:
new_val = new_col2[i - 1]
else:
new_val = ""
new_col2.append(new_val)
else:
d[key].append(value)
new_col2.append(value)
Updated. Now if first element is empty string, will leave it empty
– Nuts
4 mins ago
Thank you so much! it worked!
– user15051990
1 min ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thanks for the solution. I am getting error ` list index out of range on line new_val = new_col2[i - 1]`, when I am applying the same code on the real time example
– user15051990
10 mins ago