gpt4 book ai didi

python - 如何使用 pandas reshape 每第 n 行的数据?

转载 作者:行者123 更新时间:2023-11-30 22:42:26 25 4
gpt4 key购买 nike

我需要帮助来 reshape 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

我希望得到的是这种形式,其中只有“Brick”列中的数据将被 reshape 。

[['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("test.csv")

for i in range(0, len(df)):
slct = df.head(10)
result = slct['Brick'].reshape(2,5)

print result

该脚本仅打印以下结果

[['ww' 'ee' 'qq' 'xx' 'dd']
['gg' 'hh' 'tt' 'yy' 'uu']]

我希望它打印从第0行到第9行、第10行到第19行、第20行到第29行等等的数据...

我已经完成了 pandas 教程,但没有找到任何看起来与我想要的类似的示例。

感谢您的帮助

最佳答案

您需要使用模运算符来“批量” reshape 您的列。你走在正确的轨道上。您只需要另一个迭代器来执行模运算。

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

输出:

[['xx' 'yy' 'xa' 'bd' 'ev']
['bb' 'oo' 'pp' 'qq' 'bn']]
[['nv' 'bn' 'rr' 'qw' 'bn']
['cd' 'fd' 'bv' 'nm' 'ty']]

关于python - 如何使用 pandas reshape 每第 n 行的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42150652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com