python - 如何从具有条件的另一列中提取值?
问题描述
我想根据另一列中的值创建一列。我找到了这种方法,但我认为这不会奏效,因为我需要在“抽象”数据之前检查所有“Unique_String”值。
我想要什么?
我想通过我的“文本”列“循环”(?),看看是否有可用的数据。如果没有,它应该查看“Unique_String”列,并抽象(如果可用)值,并将其粘贴到 Text 列中。
数据
我有一个这样的数据框:
Unique_String Text
AAA Here is text!
AAA nan
BBB nan
BBB Here is text as well!
BBB Feyenoord
CCC nan
CCC nan
所需的输出是:
Unique_String Text
AAA Here is text!
AAA Here is text!
BBB Here is text as well!
BBB Here is text as well!
BBB Feyenoord
CCC nan
CCC nan
非常感谢!
解决方案
这是每组前向和后向填充的必要调用函数:
df['Text'] = df.groupby('Unique_String')['Text'].apply(lambda x: x.ffill().bfill())
print (df)
Unique_String Text
0 AAA Here is text!
1 AAA Here is text!
2 BBB Here is text as well!
3 BBB Here is text as well!
4 BBB Feyenoord
5 CCC NaN
6 CCC NaN
推荐阅读
- c# - C#,让“某物”在二维数组中一直向前移动?
- centos - 使用 rpmbuild 时如何更改 RPM 的目的地
- sql-server - SQL Server 2014,如何从字符串末尾提取公寓单元值
- docker - 如何更新我的 docker 服务/堆栈使用的最新图像?
- r - 为 ggplot 操作用户上传的数据 - Shiny
- r - R文件观察器总是读入文件
- php - 如何使用 PDO Fetch 方法从 PHP 中的数据库中获取特定的一组值?
- php - 如何在数组内foreach数组
- python - 在绘图表面 python 上使用条件着色
- pdf - MigraDoc 输出到 RTF 不同于 PDF