我想创建一个多索引的数据框,以便我可以以更有条理的方式计算值。
我知道现在有一个更优雅的解决方案,但我一直在努力寻找它。我发现的大多数东西都涉及系列和元组。我刚接触熊猫(和编程),这是我第一次尝试使用/创建多索引。
在以csv格式下载人口普查数据并创建具有相关字段的数据框后,我得到了:
county housingunits2010 housingunits2012 occupiedunits2010 occupiedunits2012
8001 120 200 50 100
8002 100 200 75 125
最后,我想:
id Year housingunits occupiedunits
8001 2010 120 50
2012 200 100
8002 2010 100 75
2012 200 125
然后能够从计算值(即,年份之间的差异,%变化)和其他数据框中添加列,从而按县和年份进行合并匹配。
我想出了一种使用我学到的基本方法的变通办法(请参阅下文),但是……这当然不是很优雅。任何建议,将不胜感激。
首先创建两个差异数据帧
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
谢谢!
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)
给
label year county
housingunits 2010 8001 120
8002 100
2012 8001 200
8002 200
occupiedunits 2010 8001 50
8002 75
2012 8001 100
8002 125
Name: count, dtype: int64
如果您想在DataFrame
通话中reset_index()
:
print(s.reset_index())
产量
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句