首页 > 解决方案 > Python:将数据框的 2 列附加在一起

问题描述

我正在使用 pandas 将 csv 文件加载到数据框中。

我的数据框看起来像这样:

col1       col2       col3         
1           4           1 
2           5           2
3           6           3

我希望将 2 列附加到一个新列中:

  col1       col2        col3       col4   
    1           4           1         1
    2           5           2         2
    3           6           3         3
                                      4
                                      5 
                                      6

col4 需要通过将 col1 和 col2 的内容附加在一起来创建。

我怎样才能在熊猫/python中做到这一点?

编辑

df = df.reset_index(drop=True)

s = df['full_name'].append(df['alt_name'], ignore_index=True).rename('combined_names')
df = df.join(s, how='outer')

df = df.reset_index(drop=True)

s = df['full_address'].append(df['alt_add'], ignore_index=True).rename('combined_address')
df = df.join(s, how='outer')

标签: pythonpandasdataframedata-science

解决方案


首先使用Series.appendor concatwith renamefor newSeries然后添加到原始 by DataFrame.joinor concat

s = df['col1'].append(df['col2'], ignore_index=True).rename('col4')
#alternative
#s = pd.concat([df['col1'], df['col2']], ignore_index=True).rename('col4')

df1 = df.join(s, how='outer')
#alternative
#df1 = pd.concat([df, s], axis=1)

print (df1)

   col1  col2  col3  col4
0   1.0   4.0   1.0     1
1   2.0   5.0   2.0     2
2   3.0   6.0   3.0     3
3   NaN   NaN   NaN     4
4   NaN   NaN   NaN     5
5   NaN   NaN   NaN     6

最后为了避免转换为浮点数是可能的使用:

df1 = df1.astype('Int64')
print (df1)
   col1  col2  col3  col4
0     1     4     1     1
1     2     5     2     2
2     3     6     3     3
3  <NA>  <NA>  <NA>     4
4  <NA>  <NA>  <NA>     5
5  <NA>  <NA>  <NA>     6

或者将缺失值转换为空字符串(如果需要稍后通过某种数字方法处理 df 应该是什么问题):

df1 = df1.fillna('')
print (df1)

  col1 col2 col3  col4
0    1    4    1     1
1    2    5    2     2
2    3    6    3     3
3                    4
4                    5
5                    6

编辑:

df = df.reset_index(drop=True)

s1 = df['full_name'].append(df['alt_name'], ignore_index=True).rename('combined_names')
s2 = df['full_address'].append(df['alt_add'], ignore_index=True).rename('combined_address')

df1 = pd.concat([df, s1, s2], axis=1)

推荐阅读