当你有太多的列的时候,融化(unpivot)数据帧?

2024-10-02 00:31:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含以下列的数据帧-

social_media.columns
Index(['respid', 'sample', 'comp', 'int_date', 'lang', 'cregion', 'state',
       'density', 'sfips', 'usr', 'qs1', 'sex', 'eminuse', 'intmob', 'intfreq',
       'snsint2', 'home4nw', 'bbhome1', 'bbhome2', 'device1a', 'smart2', 'q20',
       'bbsmart1', 'bbsmart2', 'bbsmart3a', 'bbsmart3b', 'bbsmart3c',
       'bbsmart3d', 'bbsmart3e', 'bbsmart3f', 'bbsmart3foe@', 'bbsmart4',
       'web1a', 'web1b', 'web1c', 'web1d', 'web1e', 'web1f', 'web1g', 'web1h',
       'web1i', 'sns2a', 'sns2b', 'sns2c', 'sns2d', 'sns2e', 'device1b',
       'device1c', 'device1d', 'books1', 'books2a', 'books2b', 'books2c',
       'age', 'marital', 'educ2', 'emplnw', 'hisp', 'racem1', 'racem2',
       'racem3', 'racem4', 'racecmb', 'birth_hisp', 'inc', 'party', 'partyln',
       'hh1', 'hh3', 'ql1', 'ql1a', 'qc1', 'weight', 'cellweight'],
      dtype='object')

我只想融化与web1a,web1b----web1i相关的列,并希望其他列保持原样。我知道我必须指定我不想取消粘贴的所有列,我必须将它们包含在函数的id\u vars参数中,但是您可以看到有许多列我必须复制和粘贴。你知道吗

有没有更简单的方法来实现这一点?你知道吗


Tags: columns数据sampledateindex粘贴socialmedia
1条回答
网友
1楼 · 发布于 2024-10-02 00:31:50

我们可以使用^{}和正则表达式来解决您选择某些列的问题:

案例1:使用web:

选择所有列
social_media.filter(like='web').columns

Index(['web1a', 'web1b', 'web1c', 'web1d', 'web1e', 'web1f', 'web1g', 'web1h',
       'web1i'],
      dtype='object')

案例2:选择名称中没有web的所有列:

social_media.filter(regex='^[^web]').columns

Index(['respid', 'sample', 'comp', 'int_date', 'lang', 'cregion', 'state',
       'density', 'sfips', 'usr', 'qs1', 'sex', 'intmob', 'intfreq', 'snsint2',
       'home4nw', 'device1a', 'smart2', 'q20', 'sns2a', 'sns2b', 'sns2c',
       'sns2d', 'sns2e', 'device1b', 'device1c', 'device1d', 'age', 'marital',
       'hisp', 'racem1', 'racem2', 'racem3', 'racem4', 'racecmb', 'inc',
       'party', 'partyln', 'hh1', 'hh3', 'ql1', 'ql1a', 'qc1', 'cellweight'],
      dtype='object')

相关问题 更多 >

    热门问题