pandas:列格式化问题导致合并问题

时间:2016-04-27 17:33:56

标签: python regex pandas merge formatting

我有以下两个数据库:

url='https://raw.githubusercontent.com/108michael/ms_thesis/master/rgdp_catcode.merge'

df=pd.read_csv(url, index_col=0)
df.head(1)

    naics   catcode                                        GeoName  Description     ComponentName   year    GDP     state
0   22  E1600',\t'E1620',\t'A4000',\t'E5000',\t'E3000'...   Alabama     Utilities   Real GDP by state   2004    5205    AL

url='https://raw.githubusercontent.com/108michael/ms_thesis/master/mpl.Bspons.merge'
df1=pd.read_csv(url, index_col=0)

df1.head(1)    
    state   year    unemployment    log_diff_unemployment   id.thomas   party   type    date    bills   id.fec  years_exp   session     name    disposition     catcode
0   AK  2006    6.6     -0.044452   1440    Republican  sen     2006-05-01  s2686-109   S2AK00010   39  109     National Cable & Telecommunications Association     support     C4500

关于df,我不得不手动输入catcode值。我认为这就是格式化的原因。我想要的是简单地使用没有\t前缀的值。我想合并catcode, state, year上的dfs。我之前做了一个测试,其中每个单元格只有一个值的df1.catcode与另一个df.catcode的值匹配,每个单元格的值超过一个且有效。

从技术上讲,我需要做的就是在\t中的每个连续值之前丢失df.catcode,但另外,如果有人曾经做过这种类型的合并,那么任何'警告'都会学到通过经验将不胜感激。我的合并代码如下所示:

mplmerge=pd.merge(df1,df, on=(['catcode', 'state', 'year']), how='left' )

我认为这可以使用正则表达式方法完成,我现在正在查看文档。

1 个答案:

答案 0 :(得分:1)

catcode中的df列清除非常简单:

catcode_fixed = df.catcode.str.findall('[A-Z][0-9]{4}')

这将生成一个系列,其中包含每行中的catcodes列表:

catcode_fixed.head(3)
Out[195]: 
0    [E1600, E1620, A4000, E5000, E3000, E1000]
1           [X3000, X3200, L1400, H6000, X5000]
2           [X3000, X3200, L1400, H6000, X5000]
Name: catcode, dtype: object

如果我理解你想要什么,那么你需要“取消组合”这些列表。简而言之,Here就是诀窍:

catcode_fixed = catcode_fixed = catcode_fixed.apply(pd.Series).stack()
catcode_fixed.index = catcode_fixed.index.droplevel(-1)

所以,我们得到了(注意索引值):

catcode_fixed.head(12)
Out[206]: 
0    E1600
0    E1620
0    A4000
0    E5000
0    E3000
0    E1000
1    X3000
1    X3200
1    L1400
1    H6000
1    X5000
2    X3000
dtype: object

现在,放弃旧的catcode并加入新的{{p}>

df.drop('catcode',axis = 1, inplace = True)
catcode_fixed.name = 'catcode'
df = df.join(catcode_fixed)

顺便说一句,在合并数据框时,您可能还需要使用df1.reset_index()