I make a function that accepts a dataframe as input:
a = {"string": ['xxx', 'yyy'], "array": [[1,2,3,4,5,6,1,2,3,6,6,2,2,3,5,6], [2,6,6]]}
df = pd.DataFrame(a)
string array
0 xxx [1, 2, 3, 4, 5, 6, 1, 2, 3, 6, 6, 2, 2, 3, 5, 6]
1 yyy [2, 6, 6]
And returns a dataframe, where a certain delimiter number (in the example, it is 6) is the passed parameter:
string array
0 xxx [1, 2, 3, 4, 5, 6]
1 xxx [1, 2, 3, 6]
2 xxx [6]
3 xxx [2, 2, 3, 5, 6]
4 yyy [2, 6]
5 yyy [6]
Here's what I got:
def df_conversion(df, sep=None):
data = {}
idx = []
for i in range(df.shape[0]):
key = df['string'].iloc[i]
value = df['array'].iloc[i]
spl = [[]]
for item in value:
if item == sep:
spl[-1].append(item)
idx.append(key)
spl.append([])
else:
spl[-1].append(item)
del spl[-1]
if i == 0: spl_0 = spl
if i == 1: spl_0.extend(spl)
data['string'] = idx
data['array'] = spl_0
return pd.DataFrame(data)
df_conversion(df, 6)
How can I simplify the function and make it more versatile? How do I make the function faster? Thanks.