2017-03-09 78 views
3

我對熊貓和Python非常陌生。使用熊貓/ python將數據框中的兩列數字組合成單列

我有一個3226 x 61數據框,我想將兩列合併爲一個。

我想合併的兩列都是整數 - 一個有一個或兩個數字(1到52),而另一個有三個數字(例如1或001,23或023)。我需要輸出爲五位整數(例如,01001或52023)。結果整數將不會有數學運算 - 我只需要它們用於查找目的。

基於一些在這個夢幻般的現場其他職位的,我試過如下:

df['YZ'] = df['Y'].map(str) + df['Z'].map(str) 

但是,「對第一列1.00001‘1’和第二列‘001返回’,我。相信因爲做「1」海峽把它變成「1.0」,其中「001」被添加到年底

我也試過:

df['YZ'] = df['Y'].join(df['Z']) 

收到以下錯誤:

AttributeError: 'Series' object has no attribute 'join' 

我也試過:

df['Y'] = df['Y'].astype(int) 
df['Z'] = df['Z'].astype(int) 
df['YZ'] = df[['Y','Z']].apply(lambda x: ''.join(x), axis=1) 

得到以下錯誤:

TypeError: ('sequence item 0: expected str instance, numpy.int32 

found', 'occurred at index 0') 

列的副本如下:

1 1 
1 3 
1 5 
1 7 
1 9 
1 11 
1 13 

據我所知,這裏有兩個問題:

  • 結合兩列
  • 獲取正確的格式(五位數)

坦率地說,我要同時不禁會最欣賞柱相結合的問題。

回答

2

我想你需要轉換列string,由zfill添加0,只是sum通過+

df['YZ'] = df['Y'].astype(str).str.zfill(2) + df['Z'].astype(str).str.zfill(3) 

樣品:

df=pd.DataFrame({'Y':[1,3,5,7], 'Z':[10,30,51,74]}) 
print (df) 
    Y Z 
0 1 10 
1 3 30 
2 5 51 
3 7 74 

df['YZ'] = df['Y'].astype(str).str.zfill(2) + df['Z'].astype(str).str.zfill(3) 
print (df) 
    Y Z  YZ 
0 1 10 01010 
1 3 30 03030 
2 5 51 05051 
3 7 74 07074 

如果需要也改變原始列:

df['Y'] = df['Y'].astype(str).str.zfill(2) 
df['Z'] = df['Z'].astype(str).str.zfill(3) 
df['YZ'] = df['Y'] + df['Z'] 
print (df) 
    Y Z  YZ 
0 01 010 01010 
1 03 030 03030 
2 05 051 05051 
3 07 074 07074 

解決方案與join

df['Y'] = df['Y'].astype(str).str.zfill(2) 
df['Z'] = df['Z'].astype(str).str.zfill(3) 
df['YZ'] = df[['Y','Z']].apply('-'.join, axis=1) 
print (df) 
    Y Z  YZ 
0 01 010 01-010 
1 03 030 03-030 
2 05 051 05-051 
3 07 074 07-074 

,在不更改原有列:

df['YZ'] = df['Y'].astype(str).str.zfill(2) + '-' + df['Z'].astype(str).str.zfill(3) 
print (df) 
    Y Z  YZ 
0 1 10 01-010 
1 3 30 03-030 
2 5 51 05-051 
3 7 74 07-074 
+0

這似乎這樣的伎倆 - 非常感謝你! – Newbie14