rha*_*ett 5 python missing-data dataframe pandas
有没有一种方法(比使用for循环更有效)用其各自行中的最大值替换Pandas DataFrame中的所有空值。
我想这就是你要找的:
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 0], 'b': [3, 0, 10], 'c':[0, 5, 34]})
a b c
0 1 3 0
1 2 0 5
2 0 10 34
Run Code Online (Sandbox Code Playgroud)
您可以使用apply, 迭代所有行,并通过使用replace为您提供预期输出的函数将 0 替换为行的最大数:
df.apply(lambda row: row.replace(0, max(row)), axis=1)
a b c
0 1 3 3
1 2 5 5
2 34 10 34
Run Code Online (Sandbox Code Playgroud)
如果您想替换NaN- 根据您的评论,这似乎是您的实际目标 -您可以使用
df = pd.DataFrame({'a': [1, 2, np.nan], 'b': [3, np.nan, 10], 'c':[np.nan, 5, 34]})
a b c
0 1.0 3.0 NaN
1 2.0 NaN 5.0
2 NaN 10.0 34.0
df.T.fillna(df.max(axis=1)).T
Run Code Online (Sandbox Code Playgroud)
屈服
a b c
0 1.0 3.0 3.0
1 2.0 5.0 5.0
2 34.0 10.0 34.0
Run Code Online (Sandbox Code Playgroud)
这可能比
df.apply(lambda row: row.fillna(row.max()), axis=1)
Run Code Online (Sandbox Code Playgroud)
请注意
df.apply(lambda row: row.fillna(max(row)), axis=1)
Run Code Online (Sandbox Code Playgroud)
在每种情况下为解释不工作在这里。
| 归档时间: |
|
| 查看次数: |
1608 次 |
| 最近记录: |