【问题标题】:Python: Append 2 columns of a dataframe togetherPython:将数据框的 2 列附加在一起
【发布时间】:2020-08-05 12:03:38
【问题描述】:

我正在使用 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 的内容附加在一起来创建。

如何在 pandas/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')

【问题讨论】:

  • 您能向我们展示一下您在代码方面的起步吗?
  • 解决方案有问题?

标签: python pandas dataframe data-science


【解决方案1】:

首先将Series.append 或concat 与rename 一起使用新的Series,然后通过DataFrame.join 或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)

【讨论】:

  • @pavster - 因为有必要只使用df1 = df.join(s, how='outer') 或只使用df1 = pd.concat([df, s], axis=1),不能同时使用;)
  • 由于某种原因,如果我两次使用此代码来组合 2 对列,第二个结果将在第一个结果下开始。例如,如果我附加 col2 和 col3,结果 (col5) 将从索引 6 开始。
  • @pavster - 我宁愿评论替代解决方案,仅使用 s = df['col1'].append(df['col2'], ignore_index=True).rename('col4') 和 df1 = df.join(s, how='outer')
  • @pavster - 在我的解决方案之前使用df = df.reset_index(drop=True)。
  • 现在运行良好!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多