【问题标题】:Make two new columns and fill them with appropriate data创建两个新列并用适当的数据填充它们
【发布时间】:2022-01-25 17:47:08
【问题描述】:

我有一个如下所示的数据集

id   Message

0    abc
1    def
2    <AGVPOS> 000, x_coor, y_coor, 000, 000...
3    abc
.    .

我想添加名为 X 和 Y 的两列,并为其中包含字符串“AGVPOS”的列填充值“x_coor”和“y_coor”,而对于没有字符串的列,将单元格留空这个字符串

类似的东西

id   Message.                                     X       Y

0    abc                                          Nan     Nan
1    def                                          Nan     Nan
2    <AGVPOS> 000, x_coor, y_coor, 000, 000...    x_coor  y_coor
3    abc                                          Nan     Nan
.    .

我试过了

df[['x','y']] = df['Message'].apply(lambda x: x.split(', ')[1:3] if ('AGVPOS' in x) else ['np.NaN','np.NaN'])

但它不起作用,我不断收到以下错误。

ValueError: Must have equal len keys and value when setting with an iterable

我想知道是否还有更有效的方法

谢谢。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我已经解决了。

    我忘记将列表转换为系列,应该这样做

    df[['x','y']] = df['Message'].apply(lambda x: pd.Series(x.split(', ')[1:3]) if 'AGVPOS' in x else pd.Series([np.NaN,np.NaN]))
    

    【讨论】:

      猜你喜欢
      • 2021-12-10
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2019-03-27
      • 1970-01-01
      • 2018-11-01
      • 2012-09-05
      相关资源
      最近更新 更多