找到具有0个值列的行并将其设置为none

时间:2018-08-17 07:49:51

标签: python-3.x pandas

数据:

f a b
5 0 1
5 1 3
5 1 3
5 6 3
5 0 0
5 1 5
5 0 0

我知道如何定位两列均为0的行,另一方面将其设置为None是一个谜。

df_o[(df_o['a'] == 0) & (df_o['d'] == 0)]
# set a and b to None

预期结果:

f a b 
5 0 1
5 1 3
5 1 3
5 6 3
5 None None
5 1 5
5 None None

5 个答案:

答案 0 :(得分:4)

如果通过设计将数值None转换为NaN,将整数转换为float,则

df_o.loc[(df_o['a'] == 0) & (df_o['b'] == 0), ['a','b']] = None

print (df_o)
     a    b
0  0.0  1.0
1  1.0  3.0
2  1.0  3.0
3  6.0  3.0
4  NaN  NaN
5  1.0  5.0
6  NaN  NaN

另一种使用DataFrame.all的解决方案,用于检查每行是否有True的所有axis=1

df_o.loc[(df_o[['a', 'b']] == 0).all(axis=1), ['a','b']] = None
print (df_o)
     a    b
0  0.0  1.0
1  1.0  3.0
2  1.0  3.0
3  6.0  3.0
4  NaN  NaN
5  1.0  5.0
6  NaN  NaN

详细信息

print ((df_o[['a', 'b']] == 0))
       a      b
0   True  False
1  False  False
2  False  False
3  False  False
4   True   True
5  False  False
6   True   True

print ((df_o[['a', 'b']] == 0).all(axis=1))
0    False
1    False
2    False
3    False
4     True
5    False
6     True
dtype: bool

答案 1 :(得分:0)

我能想到的一种方法就是这样。创建数据框的额外副本,并在将主数据框的值设置为None时单独检查两者。不是最干净的解决方案,但:

import pandas as pd
import numpy as np

df = pd.DataFrame()

df['f'] = [5,5,5,5,5,5,5]
df['a'] = [0,1,1,6,0,1,0]
df['b'] = [1,3,3,3,0,5,0]

df1 = df.copy()
df['a'] = np.where((df.a == 0) & (df.b == 0), None, df.a)
df['b'] = np.where((df1.a == 0) & (df1.b == 0), None, df.b)
print(df)

输出:

   f     a     b
0  5     0     1
1  5     1     3
2  5     1     3
3  5     6     3
4  5  None  None
5  5     1     5
6  5  None  None

答案 2 :(得分:0)

df.replace(0, np.nan)-获得NaN(可能更有用) df.replace(0, 'None')-您真正想要的

答案 3 :(得分:0)

这当然不是最优雅的方法,但是也许有帮助。

import pandas as pd
data = {'a': [0,1,1,6,0,1,0],
        'b':[1,3,3,3,0,5,0]}

df_o = pd.DataFrame.from_dict(data)
df_None = df_o[(df_o['a'] == 0) & (df_o['b'] == 0)]
df_o.loc[df_None.index,:] = None
print(df_o)

出局:

    a    b
0  0.0  1.0
1  1.0  3.0
2  1.0  3.0
3  6.0  3.0
4  NaN  NaN
5  1.0  5.0
6  NaN  NaN

答案 4 :(得分:0)

这就是我要做的:

import pandas as pd


a = pd.Series([0, 1, 1, 6, 0, 1, 0])
b = pd.Series([1, 3, 3, 3, 0, 5 ,0])

data = pd.DataFrame({'a': a, 'b': b})


v = [[data[i][j] for i in data] == [0, 0] for j in range(len(data['a']))]   # spot null rows

a = [None if v[i] else a[i] for i in range(len(a))]
b = [None if v[i] else b[i] for i in range(len(b))]

data = pd.DataFrame({'a': a, 'b': b})


print(data)

输出:

     a    b
0  0.0  1.0
1  1.0  3.0
2  1.0  3.0
3  6.0  3.0
4  NaN  NaN
5  1.0  5.0
6  NaN  NaN