簡體   English   中英

過濾熊貓數據幀中的字符串

[英]Filtering out string in a Panda Dataframe

我有以下公式用於計算我的Dataframe中的數據。 數據幀由下載的數據組成。 我的索引由日期組成,第一行只包含字符串..

cols = df.columns.values.tolist()
weight = 
pd.DataFrame([df[col] / df.sum(axis=1) for col in df], index=cols).T
std = pd.DataFrame([df.std(axis=1) for col in df], index=cols).T


                       A      B      C       D      E
2006-04-27 00:00:00   'dd'  'de'   'ede'   'wew'  'were'                     
2006-04-28 00:00:00  69.62  69.62  6.518   65.09  69.62
2006-05-01 00:00:00   71.5   71.5  6.522   65.16   71.5
2006-05-02 00:00:00  72.34  72.34  6.669   66.55  72.34
2006-05-03 00:00:00  70.22  70.22  6.662   66.46  70.22
2006-05-04 00:00:00  68.32  68.32  6.758   67.48  68.32
2006-05-05 00:00:00     68     68  6.805   67.99     68
2006-05-08 00:00:00  67.88  67.88  6.768   67.56  67.88

我遇到的問題是我使用的公式似乎並沒有忽略索引以及第一個只有'字符串'的索引行。 因此,我得到以下重量公式的錯誤:

TypeError:無法將類型'Timestamp'與'str'類型進行比較

我得到std公式的以下錯誤:

ValueError:對象類型沒有名為1的軸

您可以過濾行以計算重量和標准差,如下所示:

df_string = df.iloc[0]                       # Assign First row to DF
df_numeric = df.iloc[1:].astype(float)       # Assign All rows after first row to DF

cols = df_numeric.columns.values.tolist()

計算:

weight = pd.DataFrame([df_numeric[col] / df_numeric.sum(axis=1) for col in df_numeric],    
                       index=cols).T
weight

圖片

std = pd.DataFrame([df_numeric.std(axis=1) for col in df_numeric],index=cols).T
std

圖片

要重新分配,將std值說回原始DF ,您可以:

df_string_std = df_string.to_frame().T.append(std)  
df_string_std

圖片


由於OP難以復制結果,以下是使用的DF的完整摘要:

df.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 8 entries, 2006-04-27 to 2006-05-08
Data columns (total 5 columns):
A    8 non-null object
B    8 non-null object
C    8 non-null object
D    8 non-null object
E    8 non-null object
dtypes: object(5)
memory usage: 384.0+ bytes

df.index
DatetimeIndex(['2006-04-27', '2006-04-28', '2006-05-01', '2006-05-02',
               '2006-05-03', '2006-05-04', '2006-05-05', '2006-05-08'],
               dtype='datetime64[ns]', name='Date', freq=None)

使用DF

df

圖片

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM