[英]Dropping NaN from several Pandas Series, then concatenate
The data frame looks like:数据框如下所示:
import pandas as pd
import numpy as np # used for the nan values
data = {'card_name': ['Diamonds', 'Clovers', 'HorseShoe'], '$20': [1000.0, 10.0, np.nan], '$25': [500.0, np.nan, 1873.0], '$30': [25, 213, 4657], '$40': [np.nan, 2199.0, np.nan], '$50': [1500.0, np.nan, 344.0], '$70': [np.nan, 43.0, 239.0], '$75': [30.0, 2.0, np.nan], '$100': [1.0, np.nan, 748.0]}
df = pd.DataFrame(data)
card_name $20 $25 $30 $40 $50 $70 $75 $100
0 Diamonds 1000 500 25 NaN 1500 NaN 30 1
1 Clovers 10 NaN 213 2199 NaN 43 2 NaN
2 HorseShoe NaN 1873 4657 NaN 344 239 NaN 748
Make a row into a Series, dropping NaNs, and then turning it into a DataFrame:将一行变成一个系列,删除 NaN,然后将其变成 DataFrame:
Diamonds = df.iloc[0]
Diamonds = Diamonds.dropna()
Diamonds.to_frame()
(Output of the first row as a Series with no NaN) (第一行的输出为没有 NaN 的系列)
card_name Diamonds
$20 1000
$25 500
$30 25
$50 1500
$75 30
$100 1
How do I do this for all the rows without having to retype the code, above, over and over?我如何为所有行执行此操作,而不必一遍又一遍地重新键入代码?
Then how to concatenate along the 0-axis to make a new DataFrame of the new Series' without NaNs?那么如何沿 0 轴连接以制作没有 NaN 的新系列的新 DataFrame?
I'm using Python and Pandas我正在使用 Python 和 Pandas
Try with stack
尝试使用stack
s = df.set_index('card_name').stack()
s.loc['Diamonds']
$20 1000.0
$25 500.0
$30 25.0
$50 1500.0
$75 30.0
$100 1.0
dtype: float64
Update更新
s.loc['Diamonds'].reset_index(name='Diamonds')
index Diamonds
0 $20 1000.0
1 $25 500.0
2 $30 25.0
3 $50 1500.0
4 $75 30.0
5 $100 1.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.