在dict中更改数据帧

问题描述 投票:4回答:3

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

让我们考虑最简单的情况并创建两个数据帧并从中构造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中的DataFrames中排除行,例如B列中的值为零或为负的行。

我试过以下代码:

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

要么:

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

但它不起作用。

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

python pandas dictionary for-loop
3个回答
1
投票

将你的循环改为:

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)

2
投票

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

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

否则,你将不断覆盖变量df而不是将其存储在任何地方。


1
投票

如果您的所有数据帧都具有一致的索引,则应将它们与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

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

df.query('B > 0')

                      A         B         C         D
d1 2013-01-01 -0.701856  1.804441 -1.224499 -0.997452
   2013-01-04 -0.352034  0.200128  0.411482  1.058941
   2013-01-05 -0.103345  0.119615  0.251884 -0.108792
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-06  0.060094  0.610622  0.192916 -1.411557
© www.soinside.com 2019 - 2024. All rights reserved.