首页 > 解决方案 > 处理用于处理 NAN 和 NAT 列的 python 代码的 Pythonic 方式

问题描述

我有一个包含多列的大型数据集,在这些列中的每一列中都有 4 个单独的列。

为方便起见,Dataframe 中的列是 US.A、US.B、US.C、BR.A、BR.B、BR.C 现在,如果 US.B 列为空,则类似地用“-”填充所有与美国相关的列如果 BR.B 为空白,则使用“-”填写 BR 相关列。

为此,我使用 Python 3 和 pandas 我编写了一个代码来运行它,但对它的外观并不特别满意,我想知道是否有更简单的方法来处理这个问题。

import pandas as pd

###Splitting the data set

df1 = df.drop(['D','E','F'], axis=1)
df2 = df.drop(['A', 'B','C'], axis=1)


###Now I tackle them individually

df1 = df1.astype(str)
df1 = df1[df1['US.B'].isnull()]
df1 = df1f.fillna(value="-")

df2 = df2.astype(str)
df2 = df2[df2['BR.B'].isnull()]
df2 = df2.fillna(value="-")

merge = pd.concat([df1, df2])

现在我将 DataFrame 转换为字符串的原因是,由于某种原因,具有“Nat”的日期列在 fillna 期间给我带来了麻烦。现在这里看起来很整洁,但我处理的是一个庞大的数据集,这会重复多次以达到结果。

数据:

1   US.A    US.B    US.C      BR.A     BR.B    BR.C
2   Foo     123  01-01-2018     Foo     324     03-05-2017
3   Bar     124  02-01-2018     Bar     325     04-05-2017
4   Foo     125  03-01-2018                         
5   Bar     126  04-01-2018     Bar     327     06-05-2017
6                               Foo     328     07-05-2017
7   Bar     128  06-01-2018     Bar     400     08-05-2017
8           100  07-01-2018     Foo     330     

结果:

1   US.A    US.B    US.C      BR.A     BR.B    BR.C
2   Foo     123  01-01-2018     Foo     324     03-05-2017
3   Bar     124  02-01-2018     Bar     325     04-05-2017
4   Foo     125  03-01-2018      -       -          -
5   Bar     126  04-01-2018     Bar     327     06-05-2017
6   -        -     -            Foo     328     07-05-2017
7   Bar     128  06-01-2018     Bar     400     08-05-2017
8           100  07-01-2018     Foo     330     

标签: python-3.xpandasdataframe

解决方案


您可以尝试以下方法:

df_US=df.filter(like='US')
df_BR=df.filter(like='BR')

pd.concat([df_US.mask(df_US['US.B'].isna(),'-'),df_BR.mask(df_BR['BR.B'].isna(),'-')],axis=1)

  US.A US.B                 US.C BR.A BR.B                 BR.C
0  Foo  123  2018-01-01 00:00:00  Foo  324  2017-05-03 00:00:00
1  Bar  124  2018-01-02 00:00:00  Bar  325  2017-05-04 00:00:00
2  Foo  125  2018-01-03 00:00:00    -    -                    -
3  Bar  126  2018-01-04 00:00:00  Bar  327  2017-05-06 00:00:00
4    -    -                    -  Foo  328  2017-05-07 00:00:00
5  Bar  128  2018-01-06 00:00:00  Bar  400  2017-05-08 00:00:00
6  NaN  100  2018-01-07 00:00:00  Foo  330                  NaT

推荐阅读