python - Pandas:如何删除以 nan 作为列名的多列?

标签 python pandas dataframe nan

根据标题,这是一个可重现的示例:

raw_data = {'x': ['this', 'that', 'this', 'that', 'this'], 
            np.nan: [np.nan, np.nan, np.nan, np.nan, np.nan], 
            'y': [np.nan, np.nan, np.nan, np.nan, np.nan],
            np.nan: [np.nan, np.nan, np.nan, np.nan, np.nan]}

df = pd.DataFrame(raw_data, columns = ['x', np.nan, 'y', np.nan])
df

   x     NaN  y    NaN
0  this  NaN  NaN  NaN
1  that  NaN  NaN  NaN
2  this  NaN  NaN  NaN
3  that  NaN  NaN  NaN
4  this  NaN  NaN  NaN

目标是仅删除以 nan 作为列名称的列(因此保留 y 列)。 dropna() 不起作用,因为它以 列中的 nan 值为条件,而不是 nan列名。

df.drop(np.nan, axis=1, inplace=True) 如果数据中只有一列以 nan 作为 col 名称,则有效,但是不像在我的数据中那样,使用 nan 作为 col 名称的多个列。

那么如何删除列名为 nan 的多个列?

最佳答案

In [218]: df = df.loc[:, df.columns.notna()]

In [219]: df
Out[219]:
      x   y
0  this NaN
1  that NaN
2  this NaN
3  that NaN
4  this NaN

关于python - Pandas:如何删除以 nan 作为列名的多列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46101714/

相关文章:

python - 整天分组python

Python:如何从 Pandas 系列的字典中获取值

python - 如何用 pandas 中两个日期之间计算的值填充列?

python - 定制和理解 GnuRadio QT GUI Vector Sink

python - 简单的向下条形图(Python 3)

python - 查找数组 B 中元素的索引与数组 A 中的元素最匹配

python - 从数据框中删除具有特定值的连续重复项

python - 如何在Python中将二进制元素的数据解析为列表列表?

r - 在 data.frame 中的列中解包和合并列表

r - 堆叠两列