【发布时间】:2019-04-09 09:35:42
【问题描述】:
python 2.7中有以下两个数据集:
df1:
D_ID D_NBR D_ID D_HR_LVL
851669006 8383 93433 IT
260969003 7337 83189 CORP
7383 8300 72521 FIN
260969003 6262 66611 No Data
919832001 22922 90111 IT
749277000 81123 53621 FIN
3353 6363 99931 No Data
df2:
U_ID U_NBR
851669006 851669
749277000 749277
749838000 788363
919832001 919832
260969003 260969
要求:
if df1.D_HR_LVL == 'IT'
then get df2.U_NBR using df2.U_ID
elif df1.D_HR_LVL == 'FIN'
then split df2.U_NBR in 3 and 2 digits
else
keep the things as it is
试过了:
a1 = df1.D_ID.astype(str).where(df1.D_HR_LVL.eq("IT"))
a2 = df1.D_ID.map(df2.set_index('U_ID').U_NBR.astype(str))
ncol = (df1.D_ID.astype(str).str.extract(r'(\d{3})(\d+)').where(df1.D_HR_LVL.eq("FIN")).rename(columns=lambda x: 'N_COL{}'.format(x+1)))
mer_df = pd.concat([df1,a1,a2,ncol],axis=1)
但出现错误:
InvalidIndexError: Reindexing only valid with uniquely valued Index objects
目标是得到以下O/P:
new_df:
D_ID D_NBR D_ID D_HR_LVL U_NBR N_Col_1 N_Col_2
851669006 8383 93433 IT 851669
260969003 7337 83189 CORP
7383 8300 72521 FIN
260969003 6262 66611 No Data
919832001 22922 90111 IT 919832
749277000 81123 53621 FIN 749277 749 27
3353 6363 99931 No Data
任何建设性的帮助/建议都非常值得赞赏。
【问题讨论】:
-
嗨@Alpha001,这个例子不是最小的(stackoverflow.com/help/minimal-reproducible-example)。如果我遇到问题,我通常会在将示例缩减为仍然失败的最小示例期间找到解决方案(或确切搜索的内容)。
标签: python pandas python-2.7 dataframe