python - 根据列的条件组合熊猫行(矢量化)
问题描述
我有这个数据框
import pandas as pd
df = pd.DataFrame({"a":[None, None, "hello1","hello2", None,"hello4","hello5","hello6", None, "hello8", None,"hello10",None ] , "b": ["we", "are the world", "we", "love", "the", "world", "so", "much", "and", "dance", "every", "day", "yeah"]})
a b
0 None we
1 None are the world
2 hello1 we
3 hello2 love
4 None the
5 hello4 world
6 hello5 so
7 hello6 much
8 None and
9 hello8 dance
10 None every
11 hello10 day
12 None yeah
所需的输出是:
a b new_text
0 Intro we we are the world
2 hello1 we we
3 hello2 love love the
5 hello4 world world
6 hello5 so so
7 hello6 much much and
9 hello8 dance dance every
11 hello10 day day yeah
我有一个功能可以做到这一点,但它在 pandas 中使用,这可能不是最好的解决方案。
def connect_rows_on_condition(df, new_col_name, text, condition):
if df[condition][0] == None:
df[condition][0] = "Intro"
df[new_col_name] = ""
index = 1
last_non_none = 0
while index < len(df):
if df[condition][index] != None:
last_non_none = index
df[new_col_name][last_non_none] = df[text][index]
elif df[condition][index] == None :
df[new_col_name][last_non_none] = df[text][last_non_none] + " " + df[text][index]
index += 1
output_df = df[df[condition].isna() == False]
return output_df
主要逻辑是,如果在“a”列中为无,则将 b 中的文本放入之前的行中。有没有不基于循环的解决方案?
解决方案
首先,创建一个描述组的系列:
grouping = df.a.notnull().cumsum()
然后,对于 a 列,我们可以使用第一个元素,对于 b 列,我们想要连接所有元素:
df.groupby(grouping).agg({'a': 'first', 'b': ' '.join})
这给出了:
a b
a
0 None we are the world
1 hello1 we
2 hello2 love the
3 hello4 world
4 hello5 so
5 hello6 much and
6 hello8 dance every
7 hello10 day yeah
如果需要,您可以将自己替换None
为"Intro"
特殊情况,因为该文本不会出现在输入中。
推荐阅读
- javascript - 如何刷新模式弹出窗口中的数据或转发到模式弹出窗口
- laravel - Laravel 5 多租户应用程序,带有用于 octoberCMS 的单个数据库
- php - 如何为 FROM 设置别名?在 php laravel 中
- python - 使用 Visual Studio 在 C++ 中嵌入 Python 代码,无需安装 Python
- symfony - Symfony 资产函数在 http url 前面添加 /
- html - 如何将所有元素放在弹性列的底部
- android - 在中心的按钮上方放置一个 ImageView
- php - 贝宝代码错误。重定向到错误 400
- java - Java 8 嵌套列表作为父项中的单例列表
- reactjs - 如何同时运行 react 和 express?