使用pandas/python将dataframe中的两列数字合并为一列
我对熊猫和蟒蛇很陌生 我有一个3226x61数据帧,我想把两列合并成一列 我想合并的两列都是整数-一列有一个或两个数字(1到52),而另一列有三个数字(例如,1或001、23或023)。我需要输出为五位整数(例如01001或52023)。将不会对结果整数进行数学运算-我只需要它们用于查找目的 根据这个很棒的网站上的一些其他帖子,我尝试了以下方法:使用pandas/python将dataframe中的两列数字合并为一列,pandas,Pandas,我对熊猫和蟒蛇很陌生 我有一个3226x61数据帧,我想把两列合并成一列 我想合并的两列都是整数-一列有一个或两个数字(1到52),而另一列有三个数字(例如,1或001、23或023)。我需要输出为五位整数(例如01001或52023)。将不会对结果整数进行数学运算-我只需要它们用于查找目的 根据这个很棒的网站上的一些其他帖子,我尝试了以下方法: df['YZ'] = df['Y'].map(str) + df['Z'].map(str) 但第一列为“1”,第二列为“001”,返回“1.000
df['YZ'] = df['Y'].map(str) + df['Z'].map(str)
但第一列为“1”,第二列为“001”,返回“1.00001”,我相信,因为将“1”设为str会将其转换为“1.0”,并将“001”添加到末尾
我也试过:
df['YZ'] = df['Y'].join(df['Z'])
df['Y'] = df['Y'].astype(int)
df['Z'] = df['Z'].astype(int)
df['YZ'] = df[['Y','Z']].apply(lambda x: ''.join(x), axis=1)
获取以下错误:
AttributeError: 'Series' object has no attribute 'join'
TypeError: ('sequence item 0: expected str instance, numpy.int32
found', 'occurred at index 0')
我也试过:
df['YZ'] = df['Y'].join(df['Z'])
df['Y'] = df['Y'].astype(int)
df['Z'] = df['Z'].astype(int)
df['YZ'] = df[['Y','Z']].apply(lambda x: ''.join(x), axis=1)
获取以下错误:
AttributeError: 'Series' object has no attribute 'join'
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
我知道这里有两个问题:
- 合并两列
- 获取正确的格式(五位数)
坦率地说,我需要这两方面的帮助,但我非常感激列组合问题。我认为您需要将列转换为
字符串,添加0
,然后简单地求和+
:
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
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
使用连接的解决方案
:
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['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
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