简体   繁体   中英

Pandas merge data frames

I have a data frame where I have a column with nan values

I filtered them:

X_train = data[np.isnan(data[column]) == False].drop(column, 1)
y_train = data[np.isnan(data[column]) == False][column]
X_test = data[np.isnan(data[column]) == True].drop(column, 1)
y_test = data[np.isnan(data[column]) == True][column]

Then with some complex algorithm I predict y_test values. And then I want to merge these DataFrames with correct order. For example:

X, y
1, 1
12, nan
2, 3
5, nan
7, 34

y_test will have 2 values. For example after algorith is ended y_test == [2, 43]

Then I want to create following DataFrame:

X, y
1, 1
12, 2
2, 3
5, 43
7, 34

You could use

mask = np.isnan(data[column])
data.loc[mask, column] = [2, 43]

to assign the values to the original DataFrame, data :

import numpy as np
import pandas as pd

nan = np.nan
data = pd.DataFrame({'X': [1, 12, 2, 5, 7], 'y': [1.0, nan, 3.0, nan, 34.0]})
column = 'y'
mask = np.isnan(data[column])
X_train = data[~mask].drop(column, axis=1)
y_train = data.loc[~mask, column]
X_test = data[mask].drop(column, axis=1)
y_test = data.loc[mask, column]

data.loc[mask, column] = [2, 43]
print(data)

yields

    X   y
0   1   1
1  12   2
2   2   3
3   5  43
4   7  34

只需将y_test分配给缺少的值即可。

df.loc[df['y'].isnull(), 'y'] = y_test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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