【问题标题】:How to create another column in python pandas from the current table?如何从当前表在 python pandas 中创建另一列?
【发布时间】:2021-06-13 12:39:21
【问题描述】:

我有下表:

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),如果它是 TYPE-B,那么它应该是 www.website.com/xyz/AB035。输出表应如下所示:

我该怎么做?

【问题讨论】:

  • 添加栏看起来怎么样?

标签: python pandas dataframe hyperlink extract


【解决方案1】:

使用字典中的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

【讨论】:

  • @jezael 感谢您的帮助。如果我尝试实现,则会出现以下错误 TypeError: can only concatenate str (not "int") to str.
  • @MuSu18 - 将 df['ColumnB'] 更改为 df['ColumnB'].astype(str)
猜你喜欢
  • 2018-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-31
  • 2017-06-14
  • 2021-12-18
  • 1970-01-01
  • 2018-01-31
相关资源
最近更新 更多