Reputation: 423
I have a list 'lst1' and wanted to append multiple values in a single line if exist. Can anyone help me out with this.
lst1 = [['cnl','fb123','ins54'],['ins45'],['abc','xyz'],['abc','xyz','fb765','ins567']]
adn = ['ab','cc']
fb = []
ins = []
otr = []
for lnk in lst1:
for lnk2 in lnk:
if 'fb' in lnk2:
try:
fb.append(lnk2)
except:
fb.append("")
elif 'ins' in lnk2:
try:
ins.append(lnk2)
except:
ins.append("")
elif ('fb' or 'ins') not in lnk2:
try:
otr.append(lnk2)
except:
otr.append("")
data = {}
data = {'fb': fb, 'ins': ins, 'otr': otr, 'adn': adn}
result = pd.DataFrame(dict([(k,pd.Series(v)) for k,v in data.items()]))
result.to_csv("raw_data.csv", index = False)
Expected Output:
fb ins otr adn
0 fb123 ins54 cnl ab
1 ins45 cc
2 abc,xyz
3 fb765 ins567 abc,xyz
Even, I have tried with 'extend' function but unable to get the desired output.
Upvotes: 0
Views: 206
Reputation: 452
I don't understand why in the output example the third and fourth lines are empty ? And why are 'abc, xyz' in the second line?
Implemented based only on the description. If you want to exclude duplication, you can additionally transform the *_check
list to set .
import pandas as pd
lst1 = [['cnl', 'fb123', 'ins54'], ['ins45'], ['abc', 'xyz'], ['abc', 'xyz', 'fb765', 'ins567']]
adn = ['ab', 'cc']
fb = []
ins = []
otr = []
for lnk in lst1:
fb_check = [word for word in lnk if word.startswith('fb')]
ins_check = [word for word in lnk if word.startswith('ins')]
otr_check = [word for word in lnk if not word.startswith('fb') and not word.startswith('ins')]
fb.append(','.join(fb_check) if fb_check else '')
ins.append(','.join(ins_check) if ins_check else '')
otr.append(','.join(otr_check) if otr_check else '')
while len(adn) != len(fb):
adn.append('')
data = {'fb': fb, 'ins': ins, 'otr': otr, 'adn': adn}
result = pd.DataFrame(dict([(k, pd.Series(v)) for k, v in data.items()]))
print(result)
result.to_csv("raw_data.csv", index=False)
Output:
fb ins otr adn
0 fb123 ins54 cnl ab
1 ins45 cc
2 abc,xyz
3 fb765 ins567 abc,xyz
Upvotes: 1