从csv人口普查中创建多重指数

2024-09-28 03:25:10 发布

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

我想创建一个多索引的数据帧,这样我就可以以一种更有组织的方式计算值。在

我知道有一个更优雅的解决方案,但我正在努力寻找。我发现的大多数东西都涉及序列和元组。我对pandas(和编程)相当陌生,这是我第一次尝试使用/创建多索引。在

将人口普查数据下载为csv并创建包含相关字段的数据帧后,我有:

county housingunits2010 housingunits2012 occupiedunits2010 occupiedunits2012
8001   120              200              50                100
8002   100              200              75                125

最后我想说:

^{pr2}$

然后能够从计算值(即年之间的差异,%change)和其他数据帧中添加列,以匹配按县和年进行的合并。在

我用我学过的基本方法想出了一个解决办法(见下文),但是……它肯定不优雅。任何建议都将不胜感激。在

首先创建两个diff数据帧

df3 = df2[["county_id","housingunits2012"]]
df4 = df2[["county_id","housingunits2010"]]

添加年份列

df3['year'] = np.array(['2012'] * 7)
df4['year'] = np.array(['2010'] * 7)
df3.columns = ['county_id','housingunits','year']
df4.columns = ['county_id','housingunits','year']

附加

df5 = df3.append(df4)

写入csv

df5.to_csv('/Users/ntapia/df5.csv', index = False)

阅读和排序

df6 = pd.read_csv('/Users/ntapia/df5.csv', index_col=[0, 2])
df6.sort_index(0)

结果(实际数据):

                      housingunits
county_id year              
8001      2010        163229
          2012        163986
8005      2010        238457
          2012        239685
8013      2010        127115
          2012        128106
8031      2010        285859
          2012        288191
8035      2010        107056
          2012        109115
8059      2010        230006
          2012        230850
8123      2010         96406
          2012         97525

谢谢!在


Tags: csv数据idindexnparrayyeardf2
1条回答
网友
1楼 · 发布于 2024-09-28 03:25:10
import re
df = df.set_index('county')
df = df.rename(columns=lambda x: re.search(r'([a-zA-Z_]+)(\d{4})', x).groups())
df.columns = MultiIndex.from_tuples(df.columns, names=['label', 'year'])
s = df.unstack()
s.name = 'count'
print(s)

给予

^{pr2}$

如果您想在DataFrame调用reset_index()中使用:

^{3}$

收益率

           label  year  county  numunits
0   housingunits  2010    8001       120
1   housingunits  2010    8002       100
2   housingunits  2012    8001       200
3   housingunits  2012    8002       200
4  occupiedunits  2010    8001        50
5  occupiedunits  2010    8002        75
6  occupiedunits  2012    8001       100
7  occupiedunits  2012    8002       125

相关问题 更多 >

    热门问题