python - Pandas:与 nan 的操作

标签 python pandas dataframe

假设我使用 pandas 生成以下内容:

df = pd.DataFrame(np.ones(25).reshape((5,5)),index = ['A','B','C','D','E'])
df1 = pd.DataFrame(np.ones(25).reshape((5,5))*2,index = ['A','B','C','D','E'])
df[2] = np.nan
df1[3] = np.nan
df[4] = np.nan
df1[4] = np.nan
df2 = df+df1
print(df2)

     0    1   2   3   4
A  3.0  3.0 NaN NaN NaN
B  3.0  3.0 NaN NaN NaN
C  3.0  3.0 NaN NaN NaN
D  3.0  3.0 NaN NaN NaN
E  3.0  3.0 NaN NaN NaN

我需要做什么才能得到这个?

    0   1   2   3     4
A   3   3   2   1   NaN
B   3   3   2   1   NaN
C   3   3   2   1   NaN
D   3   3   2   1   NaN
E   3   3   2   1   NaN

最佳答案

使用 DataFrame.add methodfill_value 参数:

fill_value : None or float value, default None Fill missing (NaN) values with this value. If both DataFrame locations are missing, the result will be missing.

df.add(df1, fill_value=0)
Out: 
     0    1    2    3   4
A  3.0  3.0  2.0  1.0 NaN
B  3.0  3.0  2.0  1.0 NaN
C  3.0  3.0  2.0  1.0 NaN
D  3.0  3.0  2.0  1.0 NaN
E  3.0  3.0  2.0  1.0 NaN

关于python - Pandas:与 nan 的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43551691/

相关文章:

python - 同时使用调试器和 curses?

python - Apache Airflow Dag 未列出

python - Pandas 在读取制表符分隔的数据时似乎忽略了第一列名称,给出了 KeyError

python - 在Python中使用动态列名将不同的数组保存在单个csv文件中

python - Pandas 数据框 : How to print single row horizontally?

r - 基于模板与 R 中的匹配列更改数据框列的数据类型

python - 如何从线程队列Python内部停止线程

python bdist_rpm 不使用 install_requires?

python - 在 pandas DataFrame 中计算 h-index(作者出版物的影响/生产力)的有效方法

python - 如何嵌套 numpy() 的 np.where,或者一个接一个?