pandas 基于null和blocked值将Dataframe拆分为两个

ttygqcqt  于 2023-08-01  发布在  其他
关注(0)|答案(3)|浏览(117)

我有一个dataframe,并希望分裂成两个基于多列的dataframe。
df应该有没有空列和状态是的所有行。其余应在df_null上

df = vehicle.csv

Status  Country City     Year 
Yes     USA     New York 2001
Yes     Canada           2001
Yes     France  Paris    
No              Rio      1843
No      Germany Berlin   2008
Yes                      2004

# df_null has all the rows with null in the three columns
df_null = df[~df[['Country', 'City', 'Year']].notnull().all(1)]

# df has all columns with not null and status = yes
df = df[df[['Country', 'City', 'Year']].notnull().all(1)]

df = df.loc[df['Status'] == 'Yes']

result = pd.concat([df, df_null])

字符串
德国行不在结果数据框上,因为它被Status = Yes过滤掉了。

7vux5j2d

7vux5j2d1#

你可以用下面的代码创建一个binary mask

# Import Data
df = pd.DataFrame(
    [
        ["Yes", "USA", "New York", 2001],
        ["Yes", "Canada", None, 2001],
        ["Yes", "France", "Paris", None],
        ["No", None, "Rio", 1843],
        ["No", "Germany", "Berlin", 2008],
        ["Yes", None, None, 2004],
    ],
    columns=["Status", "Country", "City", "Year"],
)

# Create Mask
valid_rows = (df[["Country", "City", "Year"]].notnull().all(1)) & (df["Status"] == "Yes")

df_null = df[~valid_rows]  # Filter by inverse of mask
df = df[valid_rows]  # Filter by mask

字符串
df的输出如下:
| | 城市|年份| City | Year |
| --|--|--|--| ------------ |
| 是的,是的|美国|纽约|二OO一年| 2001 |
df_null为:
| | 城市|年份| City | Year |
| --|--|--|--| ------------ |
| 是的,是的|加拿大Name||二OO一年| 2001 |
| 是的,是的|法属|巴黎|南| nan |
| 不知道||里约|一八四三| 1843 |
| 不知道|德国|柏林|二OO八年| 2008 |
| 是的,是的|||二OO四年| 2004 |

h5qlskok

h5qlskok2#

这就是你要找的吗?

# Import pandas library 
import pandas as pd 
import numpy as np
# initialize list of lists 
data = [['Yes', 'USA', 'New York' ,2001 ],['Yes', 'Canada','',2001 ], ['Yes', 'France', 'Paris' ,'' ], ['No','' , 'Rio' ,1843 ],['No', 'Germany', 'Berlin' ,2008 ],['Yes', '', '' ,2004 ]] 
# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ["Status","Country","City","Year"]) 

# Adding filter conditions. 
df_new =  df.replace('', np.nan)
df_new = df_new[df_new.Status == 'Yes'].dropna()
df_null =df[(~df.isin(df_new))].dropna()
# Printing the two dataframes
print(df_new)
print(df_null)

字符串

nhn9ugyo

nhn9ugyo3#

如果你的问题陈述是基于Null值分割 Dataframe ,那么只需使用下面的代码。
DF_null = processed_records_DF[processed_records_DF['ColumnName'].isnull()]
DF_not_null = processed_records_DF[processed_records_DF['ColumnName'].notnull()]

相关问题