Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何以固定间隔分割数据帧_Python_Pandas_Dataframe_Slice - Fatal编程技术网

Python 如何以固定间隔分割数据帧

Python 如何以固定间隔分割数据帧,python,pandas,dataframe,slice,Python,Pandas,Dataframe,Slice,我是python新手,我有一个包含五个气候数据副本的列表,我想将其分为单独的副本。每个复制的长度为42734,数据帧(df)的总长度为213674 每个复制由一行分隔,其中第一个条目是“复制”。我已经在分隔线上方显示了每列数据的标题 Index year Month Day Rain Evap Max_Temp 42734 Replicate # 2 nan nan nan 我已经尝试了下面的代码,这是非常笨拙的,因为我必须生成10

我是python新手,我有一个包含五个气候数据副本的列表,我想将其分为单独的副本。每个复制的长度为42734,数据帧(df)的总长度为213674

每个复制由一行分隔,其中第一个条目是“复制”。我已经在分隔线上方显示了每列数据的标题

Index   year    Month   Day Rain    Evap    Max_Temp
42734   Replicate   #   2   nan     nan      nan 
我已经尝试了下面的代码,这是非常笨拙的,因为我必须生成100个气候复制,这是不实际的。我知道有一种更简单的方法可以做到这一点,但我还没有足够的python经验来理解它。 以下是我编写的代码:

# Import replicate .txt file into a dataframe
df=pd.read_table('5_replicates.txt',sep=r"\s*"                                 
                 ,skiprows=12,engine='python',header=None,                     
                 names =['year', 'Month', 'Day', 'Rain', 'Evap', 'Max_T'])  

len(df)
i = 42734
num_replicates = 5

## Replicate 1
replicate_1 = df[0:i]          
print "length of replicate_1:", len(replicate_1)

# Replicate 2
replicate_2 = df[i+1 : 2*i+1]    
print "length of replicate_2:", len(replicate_2)

# Replicate 3
replicate_3 = df[2*i+2 : 3*i+2] 
print "length of replicate_3:", len(replicate_3)

# Replicate 4
replicate_4 = df[3*i+3 : 4*i+3] 
print "length of replicate_4:", len(replicate_4)

# Replicate 5
replicate_5 = df[4*i+4 : 5*i+4] 
print "length of replicate_5:", len(replicate_5)

Any help would be much appreciated!
在这里,我只想说以下几点。1) ,我找到“Replicate”一词的索引,并将这些索引记录到dictionary
idx_dict
中。2) 为每个块创建一个python
范围
,它基本上索引了哪些块、哪些行在哪个复制中。3) 最后,我为每个块分配了一个复制的数量,不过一旦有了range对象,就不需要这样做了

#1) find where the word "replicate" is featured
indexes = df[df.year == 'Replicate'].index

#2) create the range objects
idx_dict = {}
for i in range(0,indexes.shape[0]-1):
    idx_dict[i] = range(indexes[i],indexes[i+1]-1)

#3) set the replicate number in some column
df.loc[:,'rep_num'] = np.nan #preset a value for the 'rep_num' column

for i in range(0, 4):
        print(i)
        df.loc[idx_dict[i],'rep_num'] = i
#fill in the NAs because my indexing algorithm isn't splendid         
df.rep_num.fillna(method='ffill', inplace=True)   
现在,您可以根据复制编号将
df
子集化,或者将部分存储在其他位置

#get the number of rows in each replicate:
In [26]: df.groupby("rep_num").count()
Out[26]:
         max_temp  rain  year
rep_num
0.0          2196  2196  2196
1.0          2196  2196  2196
2.0          2196  2196  2196
3.0          2197  2197  2197


#get the portion with the first replicate
In [27]: df.loc[df.rep_num==0,:].head()
Out[27]:
   max_temp      rain                 year  rep_num
0  0.976052  0.896358            Replicate      0.0
1 -0.875221 -1.110111  2016-01-01 01:00:00      0.0
2 -0.305727  0.495230  2016-01-01 02:00:00      0.0
3  0.694737 -0.356541  2016-01-01 03:00:00      0.0
4  0.325071  0.669536  2016-01-01 04:00:00      0.0

你在寻找一个简洁的版本来解决这个问题吗?如果是这样,你就快到了。只要利用循环构造并将“复制”存储到列表中,而不是单个变量中,就可以利用自己代码中的模式来获得
i
的倍数。您可以尝试自己编写代码来开始。如果您需要实际编码解决方案方面的帮助,请告诉我,我可以将其发布在这里。另外,100次复制是什么意思?你是说100个不同的文件还是100个数据帧部分而不是代码中的5个部分?嗨,不是5个副本,而是100个。我正试图为此编写一个for循环,但我无法解决如何每次增加切片的问题。我将代码简化为:Replicates={}fork in range(num_Replicates+1):forj in range(num_Replicates):Replicates['Replicate{0}'。format(k)]=df[ji+j:ki+j]但它只给我最后一个复制,早期的复制是空的。index=df[df.year\u rep=='replicate']。index Traceback(最近一次调用):index=df[df.year\u rep=='replicate']中的文件“”,第1行。index文件“C:\Users\white1\AppData\Local\Continuum\Anaconda2\lib\site packages\pandas\core\ops.py”,第763行,在包装器res=na_op(values,other)文件“C:\Users\white1\AppData\Local\Continuum\Anaconda2\lib\site packages\pandas\core\ops.py”中,第718行,在na_op raise TypeError(“无效类型比较”)TypeError:invalid type comparisonHi,感谢您的代码,我尝试运行它,并得到了上面的错误。不确定我做错了什么。@Emma,不幸的是,如果没有你的
df
,很难判断出是什么错了。这就是为什么在StackOverflow上,通常会用
df
的示例或其合适的示例来提问。您的
df
中没有
year\u rep
列,因此很自然,
df.year\u rep
不会退出,运行布尔运算也不起作用。改为试试
df.year=='Replicate']
。@Emma,我更新了代码以使其与您的示例更一致,试试上面的代码块,看看它们是否有效。
#get the number of rows in each replicate:
In [26]: df.groupby("rep_num").count()
Out[26]:
         max_temp  rain  year
rep_num
0.0          2196  2196  2196
1.0          2196  2196  2196
2.0          2196  2196  2196
3.0          2197  2197  2197


#get the portion with the first replicate
In [27]: df.loc[df.rep_num==0,:].head()
Out[27]:
   max_temp      rain                 year  rep_num
0  0.976052  0.896358            Replicate      0.0
1 -0.875221 -1.110111  2016-01-01 01:00:00      0.0
2 -0.305727  0.495230  2016-01-01 02:00:00      0.0
3  0.694737 -0.356541  2016-01-01 03:00:00      0.0
4  0.325071  0.669536  2016-01-01 04:00:00      0.0