如何从当前的 table 在 python pandas 中创建另一列?
How to create another column in python pandas from the current table?
我有以下 table:
ColumnA
ColumnB
ColumnC
1
AB001
TYPE-A
2
AB012
TYPE-A
3
AB035
TYPE-B
4
AB039
TYPE-B
5
AB065
TYPE-A
6
AB088
TYPE-B
我应该得到这样的输出,如果 ColumnC 是 TYPE-A,那么它应该保存为单独的列 (ColumnD),输出 www.website.com/abc/AB001 if it is TYPE-B then it should be www.website.com/xyz/AB035。输出 table 应如下所示:
我该怎么做?
按字典使用 Series.map
类型字符串并按 +
:
连接在一起
#if no match `TYPE-A` or `TYPE-B` added default value no match
s = df['ColumnC'].map({'TYPE-A':'abc','TYPE-B':'xyz'}).fillna('no match')
df['ColumnD'] = ' www.website.com/' + s + '/' + df['ColumnB'].astype(str)
print (df)
ColumnA ColumnB ColumnC ColumnD
0 1 AB001 TYPE-A www.website.com/abc/AB001
1 2 AB012 TYPE-A www.website.com/abc/AB012
2 3 AB035 TYPE-B www.website.com/xyz/AB035
3 4 AB039 TYPE-B www.website.com/xyz/AB039
4 5 AB065 TYPE-A www.website.com/abc/AB065
5 6 AB088 TYPE-B www.website.com/xyz/AB088
我有以下 table:
ColumnA | ColumnB | ColumnC |
---|---|---|
1 | AB001 | TYPE-A |
2 | AB012 | TYPE-A |
3 | AB035 | TYPE-B |
4 | AB039 | TYPE-B |
5 | AB065 | TYPE-A |
6 | AB088 | TYPE-B |
我应该得到这样的输出,如果 ColumnC 是 TYPE-A,那么它应该保存为单独的列 (ColumnD),输出 www.website.com/abc/AB001 if it is TYPE-B then it should be www.website.com/xyz/AB035。输出 table 应如下所示:
我该怎么做?
按字典使用 Series.map
类型字符串并按 +
:
#if no match `TYPE-A` or `TYPE-B` added default value no match
s = df['ColumnC'].map({'TYPE-A':'abc','TYPE-B':'xyz'}).fillna('no match')
df['ColumnD'] = ' www.website.com/' + s + '/' + df['ColumnB'].astype(str)
print (df)
ColumnA ColumnB ColumnC ColumnD
0 1 AB001 TYPE-A www.website.com/abc/AB001
1 2 AB012 TYPE-A www.website.com/abc/AB012
2 3 AB035 TYPE-B www.website.com/xyz/AB035
3 4 AB039 TYPE-B www.website.com/xyz/AB039
4 5 AB065 TYPE-A www.website.com/abc/AB065
5 6 AB088 TYPE-B www.website.com/xyz/AB088