使用:#create dataframe
df = pd.read_csv(filename, sep=';')
#split all values
df = df.applymap(lambda x: x.split('|'))
print (df)
fruit_type fruit_color fruit_weight
0 [Apple, Banana] [Red, Yellow] [2, 1]
1 [Orange] [Orange] [4]
2 [Pineapple, Grape, Watermelon] [Brown, Purple, Green] [12, 1, 15]
#get position of max weight
a = pd.DataFrame(df['fruit_weight'].values.tolist()).astype(float).idxmax(1).tolist()
print (a)
[0, 0, 2]
#convert df to dictionary
b = df.to_dict('list')
print (b)
{'fruit_weight': [['2', '1'], ['4'], ['12', '1', '15']],
'fruit_color': [['Red', 'Yellow'], ['Orange'], ['Brown', 'Purple', 'Green']],
'fruit_type': [['Apple', 'Banana'], ['Orange'], ['Pineapple', 'Grape', 'Watermelon']]}
^{pr2}$
计时:df = pd.concat([df]*1000).reset_index(drop=True)
def col(df):
df = df.applymap(lambda x: x.split('|'))
idx = df.index.repeat(df.fruit_weight.str.len())
df = df.apply(lambda x: pd.Series(np.concatenate(x.tolist())), 0)
return df.assign(idx=idx).groupby('idx', group_keys=False).apply(lambda x: x.sort_values('fruit_weight', ascending=False).head(1))
def jez(df):
df = df.applymap(lambda x: x.split('|'))
a = pd.DataFrame(df['fruit_weight'].values.tolist()).astype(float).idxmax(1).tolist()
b = df.to_dict('list')
a = {k: [k1[v1] for k1,v1 in zip(v, a)] for k, v in b.items()}
return pd.DataFrame(a)
print (col(df))
print (jez(df))
In [229]: %timeit (col(df))
1 loop, best of 3: 1.58 s per loop
In [230]: %timeit (jez(df))
100 loops, best of 3: 19.3 ms per loop