将每n行连接成一行pandas

7

我有:

pd.DataFrame({'col':['one','fish','two','fish','left','foot','right','foot']})
    col
0   one
1   fish
2   two
3   fish
4   left
5   foot
6   right
7   foot

我想将每n行(这里是每4行)连接起来并形成一个新的数据框架:
pd.DataFrame({'col':['one fish two fish','left foot right foot']})
    col
0   one fish two fish
1   left foot right foot

我正在使用Python和pandas

2个回答

10

如果存在默认的RangeIndex,则使用整数除法与聚合join

print (df.groupby(df.index // 4).agg(' '.join))
#for not RangeIndex create helper array
#print (df.groupby(np.arange(len(df)) // 4).agg(' '.join))
                    col
0     one fish two fish
1  left foot right foot

如果想要指定列 col

print (df.groupby(df.index // 4)['col'].agg(' '.join).to_frame())

1
尝试使用groupby
df['col'].groupby(np.repeat(np.arange(len(df)), 4)[:len(df)]).agg(' '.join)

输出:

0       one fish two fish
1    left foot right foot
Name: col, dtype: object

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接