简体   繁体   English

Python - 消除 numpy 数组或 pandas Z6A8064B53DF4794555570C53DF4794555570

[英]Python - Eliminating NaN values in each row of a numpy array or pandas dataframe

I have a pandas dataframe that currently looks like this我有一个 pandas dataframe 目前看起来像这样

|Eriksson| NaN    | Boeser | NaN   |
| NaN    | McDavid| NaN    | NaN   |
| ...    | ...    | ...    | ...   |

I don't care whether its converted to a Numpy array or it remains a Data Frame, but I want an output object where the rows just consist of the non NaN values like this:我不在乎它是转换为 Numpy 数组还是它仍然是一个数据帧,但我想要一个 output object ,其中行仅包含非 NaN 值,例如:

|Eriksson| Boeser|
|McDavid | NaN   |

( NaN because of the mismatched dimensions.) Is there any way to do this? NaN因为尺寸不匹配。)有没有办法做到这一点?

I think that this would do the trick for you:我认为这对你有用:

df.apply(lambda x: pd.Series(x.dropna().values), axis=1)

Example:例子:

>>> df = pd.DataFrame(np.random.randn(5,4))
>>> df.iloc[1,2] = np.NaN
>>> df.iloc[0,1] = np.NaN
>>> df.iloc[2,1] = np.NaN
>>> df.iloc[2,0] = np.NaN
>>> df
          0         1         2         3
0 -0.162388       NaN -0.299892  0.594846
1  3.165631 -1.190102       NaN -1.234934
2       NaN       NaN  0.885439 -1.714365
3 -1.622833 -1.319395 -1.716550 -0.517699
4  0.688479  0.576763  0.645344  0.708909
>>> df.apply(lambda x: pd.Series(x.dropna().values), axis=1)
          0         1         2         3
0 -0.162388 -0.299892  0.594846       NaN
1  3.165631 -1.190102 -1.234934       NaN
2  0.885439 -1.714365       NaN       NaN
3 -1.622833 -1.319395 -1.716550 -0.517699
4  0.688479  0.576763  0.645344  0.708909

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 连接每行值直到 python dataframe 中的 NaN 值 - Concatenating each row values until a NaN value in a python dataframe Python Pandas:查找包含numpy数组的数据框列中每行的最大值 - Python Pandas: Find the maximum for each row in a dataframe column containing a numpy array 使用 pandas dataframe apply 替换 numpy 数组中的行值 - Use pandas dataframe apply to replace row values from a numpy array Python:用一列numpy数组填充pandas数据帧的一行 - Python: fill a row of a pandas dataframe with a column of an numpy array 如何遍历pandas数据帧中的每一行,并在超过阈值后设置等于nan的值? - How to loop through each row in pandas dataframe and set values equal to nan after a threshold is surpassed? Python Pandas Dataframe填充NaN值 - Python Pandas Dataframe fill NaN values Python Pandas连接数据框-NaN代替值 - Python Pandas concate dataframe - NaN instead of values Python熊猫数据框获取NaN而不是值 - Python pandas dataframe getting NaN instead of values 通过将行熊猫中的NaN值与列匹配来将数据帧中的一行添加到另一行中 - Adding a row from a dataframe into another by matching columns with NaN values in row pandas python Python Pandas dataframe:获取每列的最高 n 个非 NaN 值以及这些值的索引 - Python Pandas dataframe: get highest n non-NaN values for each column and the indices for those values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM