如何使用 pandas 重塑每第n行的数据? [英] How to reshape every nth row's data using pandas?
问题描述
我需要帮助重塑csv文件中的数据,这些数据超过10000行,每行10个。例如,我有这个csv文件:
Ale Brick
1 ww
2 ee
3 qq
3 xx
5 dd
3 gg
7 hh
8 tt
9 yy
0 uu
1 ii
2 oo
3 pp
4 mm
1 ww
7 zz
1 cc
3 rr
6 tt
9 ll
我希望得到的是这种形式,将重新整形。
[['ww''ee''qq''xx''dd']
['gg''hh''tt''yy''uu']]
[['ii''oo''pp''mm''ww']
[' zz''cc''rr''tt''ll']]
我知道如何重塑数据从0到第9行,但不知道如何做到下10行。这是我的脚本:
import pandas as pd
df = pd.read_csv csv)
for i in range(0,len(df)):
slct = df.head(10)
result = slct ['Brick']。reshape (2,5)
打印结果
此脚本仅打印以下内容结果
[['ww''ee''qq''xx''dd']
['gg ''hh''tt''yy''uu']]
我希望能打印从0到第9行,第10到第19行,第20行到第29行等数据...
我已经通过了熊猫教程,但没有
感谢您的帮助
/ div>您需要使用模运算符来批量重整您的列。你在正确的轨道。
import pandas as pd
df = pd .DataFrame({'brick':['xx','yy','xa','bd','ev','bb','oo','pp','qq','bn' nv','bn','rr','qw','bn','cd','fd','bv','nm','ty']}
start = 0#set start to 0 for slicing
for i in range(len(df.index)):
if(i + 1)%10 == 0:#模运算
result = df ['brick']。iloc [start:i + 1] .reshape(2,5)
打印结果
start = i + 1#设置开始到下一个索引
输出:
[['xx''yy''xa''bd''ev']
['bb''oo''pp''qq''bn']]
[['nv' bn''rr''qw''bn']
['cd''fd''bv''nm''ty']]
I need help in reshaping a data in csv file that have over 10000 row by 10 each. For example I have this csv file :
Ale Brick 1 ww 2 ee 3 qq 3 xx 5 dd 3 gg 7 hh 8 tt 9 yy 0 uu 1 ii 2 oo 3 pp 4 mm 1 ww 7 zz 1 cc 3 rr 6 tt 9 ll
What I am hoping to get is this form where only data in 'Brick' column will be reshaped.
[['ww' 'ee' 'qq' 'xx' 'dd'] ['gg' 'hh' 'tt' 'yy' 'uu']] [['ii' 'oo' 'pp' 'mm' 'ww'] ['zz' 'cc' 'rr' 'tt' 'll']]
I know how to reshape the data from 0 until 9th row only but did not know how to do it for next 10th row. Here is my script :
import pandas as pd df = pd.read_csv("test.csv") for i in range(0, len(df)): slct = df.head(10) result = slct['Brick'].reshape(2,5) print result
This script only print the following result
[['ww' 'ee' 'qq' 'xx' 'dd'] ['gg' 'hh' 'tt' 'yy' 'uu']]
I was hoping for it to print the data from 0 to 9th row, 10th to 19th row, 20th row to 29th row and so on...
I have been through the pandas tutorial but did not find any example that looks similar to what I want.
Thank you for your help
解决方案You need to make use of the modulo operator to "batch" reshape your column. You're on the right track. You just need another iterator to do the modulo operation.
import pandas as pd df = pd.DataFrame({'brick': ['xx','yy','xa','bd','ev','bb','oo','pp','qq','bn','nv','bn','rr','qw','bn','cd','fd','bv','nm','ty']}) start = 0 # set start to 0 for slicing for i in range(len(df.index)): if (i + 1) % 10 == 0: # the modulo operation result = df['brick'].iloc[start:i+1].reshape(2,5) print result start = i + 1 # set start to next index
Output:
[['xx' 'yy' 'xa' 'bd' 'ev'] ['bb' 'oo' 'pp' 'qq' 'bn']] [['nv' 'bn' 'rr' 'qw' 'bn'] ['cd' 'fd' 'bv' 'nm' 'ty']]
这篇关于如何使用 pandas 重塑每第n行的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!