pandas 用python将一列中的多行合并为一行

xe55xuns  于 2022-12-21  发布在  Python
关注(0)|答案(1)|浏览(477)

我想将一列中的每四行合并到下一列中的一行。对于下面的 Dataframe ,它将把16行转换为4行,每行都包含值。

df = pd.DataFrame({
    'A1': [1,0,0,0,1,1,0,0,1,0,0,0,1,1,1,0]})

输出应该是,

A2:
1000
1100
1000
1110
nr7wwzry

nr7wwzry1#

注:由于第二列只有4行,而第一列有16行,因此将存在维不匹配。因此,您必须将第二列保存在第二个 Dataframe 中,或者为每个A1值重复A2标签
除此之外,这应该工作,以获得您正在寻找的A2值。

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'A1': [1,0,0,0,1,1,0,0,1,0,0,0,1,1,1,0]})

A2 = []

#loop through every fourth value
for i in range(int(len(df)/4)):
    #get the current four values
    current_four = df.iloc[i*4: (i*4) + 4]
    #convert the values to strings to join them together
    new_entry = ''.join(map(str, list(current_four['A1'])))
    A2.append(int(new_entry))
 
result_df = pd.DataFrame({'A2': A2})

相关问题