Skip to main content
 首页 » 编程设计

python之如何拆分 Pandas 中的几列数据

2025年05月04日21dflying

我有一个如下所示的数据框:

df = pd.DataFrame({'hard': [['525', '21']], 'soft': [['1525', '221']], 'set': [['5245', '271']],  'purch': [['925', '201']], \ 
                  'mont': [['555', '621']], 'gest': [['536', '251']], 'memo': [['825', '241']], 'raw': [['532', '210']]}) 
df 
 
Out: 
 
    gest        hard        memo        mont        purch       raw         set         soft 
0   [536, 251]  [525, 21]   [825, 241]  [555, 621]  [925, 201]  [532, 210]  [5245, 271] [1525, 221] 

我应该像这样拆分所有列:

df1 = pd.DataFrame() 
df1['gest_pos'] = df.gest.str[0].astype(int) 
df1['gest_size'] = df.gest.str[1].astype(int) 
df1['hard_pos'] = df.hard.str[0].astype(int) 
df1['hard_size'] = df.hard.str[1].astype(int) 
df1  
 
    gest_pos    gest_size   hard_pos    hard_size 
0   536         251         525         21 

我有 70 多列,我的方法占用了大量的空间和时间。有没有更简单的方法来完成这项工作?

谢谢!

请您参考如下方法:

不同的方法:

df2 = pd.DataFrame() 
for column in df: 
    df2['{}_pos'.format(column)] = df[column].str[0].astype(int) 
    df2['{}_size'.format(column)] = df[column].str[1].astype(int) 
print(df2)