繁体   English   中英

Pandas - 合并两列

[英]Pandas - combine two columns

我有 2 列,我们将其称为xy 我想创建一个名为xy的新列:

x    y    xy
1         1
2         2

     4    4
     8    8

不应该有任何冲突的值,但如果有,y 优先。 如果它使解决方案更容易,您可以假设x将始终为NaN ,其中y具有值。

如果你的例子是准确的,那可能很简单

df.fillna(0)      #if the blanks are nan will need this line first
df['xy']=df['x']+df['y']

注意你的列类型现在是字符串而不是数字了

df = df.apply(lambda x : pd.to_numeric(x, errors='coerce'))

df['xy'] = df.sum(1)

更多的

df['xy'] =df[['x','y']].astype(str).apply(''.join,1)

#df[['x','y']].astype(str).apply(''.join,1)
Out[655]: 
0    1.0
1    2.0
2       
3    4.0
4    8.0
dtype: object

您还可以使用 NumPy:

import pandas as pd, numpy as np

df = pd.DataFrame({'x': [1, 2, np.nan, np.nan],
                   'y': [np.nan, np.nan, 4, 8]})

arr = df.values
df['xy'] = arr[~np.isnan(arr)].astype(int)

print(df)

     x    y  xy
0  1.0  NaN   1
1  2.0  NaN   2
2  NaN  4.0   4
3  NaN  8.0   8

暂无
暂无

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

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