过滤熊猫数据帧中的字符串

时间:2016-09-17 16:25:40

标签: python pandas dataframe rows

我使用以下公式来计算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:无法比较类型'时间戳'使用类型' str'

我得到std公式的以下错误:

  

ValueError:对象类型

没有名为1的轴

1 个答案:

答案 0 :(得分:3)

您可以过滤行以计算重量和标准差,如下所示:

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

Image

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

Image

要重新分配,请将std值说回原始DF,您可以这样做:

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

Image

由于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

Image