【发布时间】:2016-08-24 23:50:33
【问题描述】:
我在尝试从表中删除 nan 列时遇到了问题。
这是按预期工作的示例:
import pandas as pd
import numpy as np
df1 = pd.DataFrame([[1, 2, 3], [4, 5, 6]],
columns=['A', 'B', 'C'],
index=['Foo', 'Bar'])
mapping1 = pd.DataFrame([['a', 'x'], ['b', 'y']],
index=['A', 'B'],
columns=['Test', 'Control'])
# rename the columns using the mapping file
df1.columns = mapping1.loc[df1.columns, 'Test']
从这里我们看到df1 中的C 列在映射文件中没有条目,因此该标题被替换为nan。
# drop the nan column
df1.drop(np.nan, axis=1)
在这种情况下,调用np.nan 会找到最终的标头并将其丢弃。
但是,在以下情况下,df.drop 不起作用:
# set up table
sample1 = np.random.randint(0, 10, size=3)
sample2 = np.random.randint(0, 5, size=3)
df2 = pd.DataFrame([sample1, sample2],
index=['sample1', 'sample2'],
columns=range(3))
mapping2 = pd.DataFrame(['foo']*2, index=range(2),
columns=['test'])
# assign columns using mapping file
df2.columns = mapping2.loc[df2.columns, 'test']
# try and drop the nan column
df2.drop(np.nan, axis=1)
nan 列仍然存在。
【问题讨论】: