简体   繁体   English

如何创建具有不丢失数据(不是 NaN)的特征、值和索引的 DataFrame?

[英]How can I create a DataFrame with feature, value and index of not missing data (not NaN's)?

I have the following Data Frame我有以下数据框

data = {'first_set_of_numbers':  [3,9,6,np.nan],
        'second_set_of_numbers': [np.nan,13,np.nan,np.nan]
       }
df = pd.DataFrame(data,columns=['first_set_of_numbers','second_set_of_numbers'], index=['A','B','C','D'])
df

在此处输入图片说明

How can I now get a new Data Frame that shows all the not missing values with their accoring feature and index?我现在如何获得一个新的数据框,显示所有未缺失的值及其相应的特征和索引? It should look like this:它应该是这样的:

在此处输入图片说明

You can use df.stack() and df.reset_index :您可以使用df.stack()df.reset_index

In [2493]: df.stack().reset_index(level=[1], name='value').rename(columns={'level_1':'feature'})
Out[2493]: 
                 feature  value
A   first_set_of_numbers    3.0
B   first_set_of_numbers    9.0
B  second_set_of_numbers   13.0
C   first_set_of_numbers    6.0

You can use df.melt with ignore_index parameter set to False and use df.dropna here.您可以使用df.melt并将ignore_index参数设置为False并在此处使用df.dropna

df.melt(ignore_index=False, var_name='features', value_name='value').dropna() 
# default values of `var_name` -> 'variable', `value_name`->'value'

                features  value
A   first_set_of_numbers    3.0
B   first_set_of_numbers    9.0
C   first_set_of_numbers    6.0
B  second_set_of_numbers   13.0

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

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