Python 删除序列为空的数据帧中的行
我在数据框中有一列。行中有空序列的:Python 删除序列为空的数据帧中的行,python,pandas,dataframe,Python,Pandas,Dataframe,我在数据框中有一列。行中有空序列的: 0 4.5 1 0.5 2 8 3 8 4
0 4.5
1 0.5
2 8
3 8
4 8
...
704 3.5
705 0.5
706 11.5
707 0.5
708 Series([], Name: price, dtype: float64)
Name: pricediff, Length: 709, dtype: object",
0 4
1 0.5
2 2.5
3 19.5
4 19.5
...
58 1
59 4
60 8.5
61 Series([], Name: price, dtype: float64)
62 Series([], Name: price, dtype: float64)
Name: pricediff, Length: 63, dtype: object",
如何删除该行或将其替换为0,而不直接执行df.drop(df.index[61])等操作,因为我有多个数据您可以检查每个元素是否为空序列,然后替换所有这些条目 首先,我们将创建一个测试数据帧
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0, 100, (3, 3)))
df[3] = [1, pd.Series([]), 5]
def make_empty_series_zero(element):
if isinstance(element, pd.Series) and len(element) == 0:
return 0
else:
return element
df.applymap(make_empty_series_nan)
因此,我们有:
0 1 2 3
0 31 29 1 1
1 86 86 71 Series([], dtype: float64)
2 86 80 21 5
0 1 2 3
0 57 58 2 1
1 96 27 8 0
2 0 43 91 5
现在,我们引入一个函数将空序列设置为0,并将其应用于数据帧
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0, 100, (3, 3)))
df[3] = [1, pd.Series([]), 5]
def make_empty_series_zero(element):
if isinstance(element, pd.Series) and len(element) == 0:
return 0
else:
return element
df.applymap(make_empty_series_nan)
将其应用于我们的数据帧后,我们有:
0 1 2 3
0 31 29 1 1
1 86 86 71 Series([], dtype: float64)
2 86 80 21 5
0 1 2 3
0 57 58 2 1
1 96 27 8 0
2 0 43 91 5
你能澄清这个例子吗?很难说什么是什么。为什么在一列中有一系列的浮动呢?