【问题标题】:How can I abstract a value from another column with a condition?如何从具有条件的另一列中提取值?
【发布时间】:2019-08-27 08:46:32
【问题描述】:

我想根据另一列中的值创建一列。我找到了这个approach,但我认为这不会起作用,因为我需要在“抽象”数据之前检查所有的“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.groupby('Unique_String')['Text'].apply(lambda x: x.ffill().bfill())

标签: python pandas data-manipulation


【解决方案1】:

这里是每组前向和后向填充的必要调用函数:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-23
    • 2018-03-30
    • 1970-01-01
    • 2022-01-19
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多