简体   繁体   English

Pandas - 根据列对行进行分组并将 NaN 替换为非空值

[英]Pandas - Group Rows based on a column and replace NaN with non-null values

I'm trying to create some aggregations with strings on my dataframe, based on a target "group-by" column.我正在尝试根据目标“分组依据”列在我的 dataframe 上使用字符串创建一些聚合。

Imagine that I have the following dataframe with 4 columns:想象一下,我有以下 dataframe 和 4 列:

在此处输入图像描述

I want to group all the rows based on column "Col1" and in the case o NaN group with the value that is not null.我想根据列“Col1”对所有行进行分组,在 o NaN 组的情况下,其值不是 null。

The desired output is like this:想要的output是这样的:

在此处输入图像描述

I also try to use a normal:我也尝试使用普通的:

import pandas as pd
from tabulate import tabulate

df = pd.DataFrame({'Col1': ['A', 'B', 'A'],
                   'Col2': ['X', 'Z', 'X'],
                   'Col3': ['Y', 'D', ''],
                   'Col4': ['', 'E', 'V'],})

print(tabulate(df, headers='keys', tablefmt='psql'))
df2 = df.groupby(['Col1'])
print(tabulate(df2, headers='keys', tablefmt='psql'))

But it doesn't group the NaN values...但它没有对 NaN 值进行分组......

How can I do this?我怎样才能做到这一点?

Thanks!谢谢!

If is possible simply question for first non missing values per groups use GroupBy.first :如果可以简单地询问每个组的第一个非缺失值,请使用GroupBy.first

df = pd.DataFrame({'Col1': ['A', 'B', 'A'],
                   'Col2': ['X', 'Z', 'X'],
                   'Col3': ['Y', 'D', np.nan],
                   'Col4': [np.nan, 'E', 'V'],})


df2 = df.groupby(['Col1'], as_index=False).first()
print (df2)
  Col1 Col2 Col3 Col4
0    A    X    Y    V
1    B    Z    D    E

Using first() is more concise and neater.使用first()更简洁明了。 An alternative but less cool approach would be:另一种但不太酷的方法是:

df.replace('', np.nan) \
.groupby('Col1', as_index=False) \
.fillna(method='bfill') \
.groupby('Col1') \
.nth(0)

Output: Output:

Col1    Col2    Col3    Col4
A   X   Y   V
B   Z   D   E

or even you may use head() instead of nth() :甚至你可以使用head()而不是nth()

df.replace('', np.nan) \
.groupby('Col1', as_index=False) \
.fillna(method='bfill') \
.groupby('Col1') \
.head(1) \ 
.set_index('Col1')

Output: Output:

Col1    Col2    Col3    Col4
A   X   Y   V
B   Z   D   E

Just use df.replace() on already initiated DataFrame to replace them with np.nan只需在已经启动的 DataFrame 上使用 df.replace() 将它们替换为 np.nan

df.replace('', np.nan)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM