【问题标题】:Pandas: Using apply to copy row values across specific columns into new columnPandas:使用 apply 将特定列中的行值复制到新列中
【发布时间】:2019-09-12 22:01:30
【问题描述】:

我正在尝试使用 apply 函数将行子集的所有值复制到新列中,但它似乎只是复制了整个数据框范围。结果,我收到了数据帧的该子集,尽管我希望 df.loc[index, 'consolidated_commentary'] 包含 all_commentary_columns 中包含的列中文本的串联版本

我的代码是:

 for index, row in df[all_commentary_columns].iterrows():
if pd.isna(row).prod():
    df.loc[index, 'new_col'] = 'good'
else:
    df.loc[index, 'new_col'] = 'bad'
    df.loc[index, 'consolidated_commentary'] = df[all_commentary_columns].apply(lambda x: x.loc[all_commentary_columns], axis=1)

【问题讨论】:

标签: python-3.x pandas


【解决方案1】:

我从我在 cmets 中引用的答案中提取了这个:

df.loc[index, 'consolidated_commentary'] = df.loc[index, all_commentary_columns].astype(str).apply(lambda x: ' '.join(' '.join(x).split()),axis=1)

【讨论】:

  • 谢谢你,虽然它似乎没有按预期连接行值:/
猜你喜欢
  • 2021-11-29
  • 2021-06-21
  • 2023-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多