更改di中的数据帧

2024-06-26 14:09:20 发布

您现在位置:Python中文网/ 问答频道 /正文

请帮助我理解如何更改字典中的数据帧。在

让我们考虑最简单的情况,创建两个数据帧并从中构造dict。在

dates = pd.date_range('20130101',periods=6)
df1 =pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD'))
df2 =pd.DataFrame(np.random.randn(6,4),index=dates,columns=list('ABCD'))
DICTOR={}
DICTOR['d1']=df1
DICTOR['d2']=df2
m=DICTOR

现在我想从dict m内的数据帧中排除行,例如B列中的值为零或负数的行。在

我尝试了以下代码:

^{pr2}$

或者:

for name,df in m.items():
    df=df[df.B>0]

但它不起作用。在

我想我的问题是由于可变/不可变的对象,但我不确定。在


Tags: columns数据dataframedfindexnprandomdict
3条回答

将循环改为:

for name,df in m.items():
     for index, row in df.iterrows():
         if df.at[index,'B']<0:
             df.drop(index,axis=0, inplace=True)

迭代时需要为字典键赋值:

for name, df in m.items():
    m[name] = df[df['B'] > 0]

否则,您将不断重写一个变量df,而不是将其存储在任何地方。在

如果所有的数据帧都有一致的索引,则应使用MultiIndex将它们保持在一起

df = pd.concat(m)

df

                      A         B         C         D
d1 2013-01-01 -0.701856  1.804441 -1.224499 -0.997452
   2013-01-02 -1.122829 -0.375963  1.476828  1.254910
   2013-01-03 -0.330781 -0.692166  1.352655 -1.296063
   2013-01-04 -0.352034  0.200128  0.411482  1.058941
   2013-01-05 -0.103345  0.119615  0.251884 -0.108792
   2013-01-06  0.690312 -1.115858 -0.271362 -0.872862
d2 2013-01-01  1.449789  0.144008 -0.445732 -0.356491
   2013-01-02  0.254142  0.102233 -0.456786  1.505599
   2013-01-03 -1.636609  0.141300 -1.458500  0.088640
   2013-01-04  0.015575  1.170128  0.229888 -0.273040
   2013-01-05  0.995011 -1.476076 -0.345353 -0.343009
   2013-01-06  0.060094  0.610622  0.192916 -1.411557

此时可以使用多种过滤方法

^{pr2}$

相关问题 更多 >