在单元格中包含多个信息的pandas透视表

2024-05-16 09:45:25 发布

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

我对熊猫不太熟悉,所以这可能是个愚蠢的问题。我试着分析以下数据:

df = pd.DataFrame({
      'Country' : ['country1', 'country2', 'country3', 'country4'],
      'Industry' : ['industry1:\$20 \n industry4:\$30', 
                    'industry10:\$100', 
                    'industry3:\$2 \n industry4:\$30 \n industry12:\$10 \n industry1:\$3',
                    'industry1:\$20 \n industry4:\$30'
                   ],})

(\n来自excel提取)

我需要将行业作为指数,将国家作为列。我的直觉是,我需要先对包含多种信息的细胞进行某种“数据解包”,但我不知道如何在熊猫身上这样做。在


谢谢大家。下面有一些答案很有效。我继续搜索,发现了一些与这个问题相关的帖子(有人把这个问题称为“爆炸熊猫行”)。在下面的线程中,有人编写了一个通用函数explode(),它是通用的,性能很好:

Split (explode) pandas dataframe string entry to separate rows


Tags: 数据dataframedfcountrypdindustryexplodecountry2
1条回答
网友
1楼 · 发布于 2024-05-16 09:45:25

您可以使用:

  • ^{}按不带Industry的所有列
  • ^{}by regex\s+\n\s+-\s+表示1个或多个空白
  • ^{}Series重塑形状
  • 再次使用不同的分隔符split
  • ^{},先删除第一级
  • rename
df = (df.set_index(['Country'])['Industry']
        .str.split('\s+\n\s+', expand=True)
        .stack()
        .str.split(r':\\\$', expand=True)
        .reset_index(level=1, drop=True)
        .reset_index()
        .rename(columns={0:'Industry', 1:'Val'})
     )   
print (df)
    Country    Industry  Val
0  country1   industry1   20
1  country1   industry4   30
2  country2  industry10  100
3  country3   industry3    2
4  country3   industry4   30
5  country3  industry12   10
6  country3   industry1    3
7  country4   industry1   20
8  country4   industry4   30

相关问题 更多 >