python - 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')
解决方案
首先使用Series.append
or concat
with rename
for newSeries
然后添加到原始 by DataFrame.join
or 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)
推荐阅读
- java - Spring 外部资源
- azure - 收到电子邮件后创建 Azure 板卡
- c# - .NET Core 3.0 迁移错误 IAsyncEnumerable
System.Interactive.Async 和 System.Runtime 中都存在 - paypal - 减少 Paypal 结帐期间的重定向次数
- ionic-framework - 列表项过多导致延迟
- javascript - jQuery计算具有值的输入字段的数量
- azure - 在 AAD 凭据下记录 API 调用
- gulp-4 - 在临时文件夹中注入文件时自动附加 src 文件夹
- javascript - 我得到 ["Yes", true]:Array 的未定义方法“名称”而不是预填充字段
- kofax - Kofax 验证规则