Fed*_*ile 5 python list append dataframe pandas
我有一个看起来像这样的数据框:
dic = {'A':['PINCO','PALLO','CAPPO','ALLOP'],
'B':['KILO','KULO','FIGA','GAGO'],
'C':[['CAL','GOL','TOA','PIA','STO'],
['LOL','DAL','ERS','BUS','TIS'],
['PIS','IPS','ZSP','YAS','TUS'],
[]]}
df1 = pd.DataFrame(dic)
Run Code Online (Sandbox Code Playgroud)
我的目标是为每一行插入元素 A
作为 column 中包含的列表的第一项C
。同时,我想将 的元素设置B
为包含在C
.
我能够通过使用以下代码行来实现我的目标:
for index, row in df1.iterrows():
try:
row['C'].insert(0,row['A'])
row['C'].append(row['B'])
except:
pass
Run Code Online (Sandbox Code Playgroud)
有没有更优雅、更有效的方法来实现我的目标,也许使用一些 Pandas 函数?我想避免 for 循环。
一个好的通用规则是尽可能避免使用apply
with ,因为迭代行的成本很高axis=1
您可以将 A 列和 B 列中的每个元素转换为列表map
,然后对各行求和。
df1['A'] = df1.A.map(lambda x: [x])
df1['B'] = df1.B.map(lambda x: [x])
df1.sum(1)
CPU times: user 3.07 s, sys: 207 ms, total: 3.27 s
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用apply
axis=1,它在我的计算机上运行 100 万行时慢了 15 倍
df1.apply(lambda x: [x['A']] + x['C'] + [x['B']], 1)
CPU times: user 48.5 s, sys: 119 ms, total: 48.6 s
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4338 次 |
最近记录: |