简体   繁体   English

将列附加到 Pandas 中的其他列

[英]Appending columns to other columns in Pandas

Given the dataframe:给定 dataframe:


d = {'col1': [1, 2, 3, 4, 7], 'col2': [4, 5, 6, 9, 5], 'col3': [7, 8, 12, 1, 11], 'col4': [12, 13, 14, 15, 16]}

What is the easiest way to append the third column to the first and the fourth column to the second? append 第三列到第一列和第四列到第二列的最简单方法是什么?

The result should look like.结果应该是这样的。


d = {'col1': [1, 2, 3, 4, 7, 7, 8, 12, 1, 11], 'col2': [4, 5, 6, 9, 5, 12, 13, 14, 15, 16],

I need to use this for a script with different column names, thus referencing columns by name is not possible.我需要将它用于具有不同列名的脚本,因此无法按名称引用列。 I have tried something along the lines of df.iloc[:,x] to achieve this.我已经尝试了 df.iloc[:,x] 的方法来实现这一点。

You can change the column names and concat :您可以更改列名和concat

pd.concat([df[['col1', 'col2']],
           df[['col3', 'col4']].set_axis(['col1', 'col2'], axis=1)])

Add ignore_index=True to reset the index in the process.添加ignore_index=True以重置进程中的索引。

Output: Output:

   col1  col2
0     1     4
1     2     5
2     3     6
3     4     9
4     7     5
0     7    12
1     8    13
2    12    14
3     1    15
4    11    16

Or, using numpy :或者,使用numpy

N = 2
pd.DataFrame(
    df
    .values.reshape((-1,df.shape[1]//2,N))
    .reshape(-1,N,order='F'),
    columns=df.columns[:N]
 )

You can use:您可以使用:

out = pd.concat([subdf.set_axis(['col1', 'col2'], axis=1)
                for _, subdf in df.groupby(pd.RangeIndex(df.shape[1]) // 2, axis=1)])
print(out)

# Output
   col1  col2
0     1     4
1     2     5
2     3     6
3     4     9
4     7     5
0     7    12
1     8    13
2    12    14
3     1    15
4    11    16

This may not be the most efficient solution but, you can do it using thepd.concat() function in pandas.这可能不是最有效的解决方案,但您可以使用 pandas 中的pd.concat() function 来实现。

First convert your initial dict d into a pandas Dataframe and then apply the concat function.首先将您的初始字典d转换为pandas Dataframe ,然后应用 concat function。

  d = {'col1': [1, 2, 3, 4, 7], 'col2': [4, 5, 6, 9, 5], 'col3': [7, 8, 12, 1, 11], 'col4': [12, 13, 14, 15, 16]}
  df = pd.DataFrame(d)
  d_2 = {'col1':pd.concat([df.iloc[:,0],df.iloc[:,2]]),'col2':pd.concat([df.iloc[:,1],df.iloc[:,3]])}

d_2 is your required dict. d_2是你需要的字典。 Convert it to a dataframe if you need it to,如果需要,将其转换为 dataframe,

df_2 = pd.DataFrame(d_2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM