我有2个数据框:
ID word
1 srv1
2 srv2
3 srv1
4 nan
5 srv3
6 srv1
7 srv5
8 nan
ID word
1 nan
2 srv12
3 srv10
4 srv8
5 srv4
6 srv7
7 nan
8 srv9
我需要的是将ID上的那两个数据帧合并,并合并列字以获得:
ID word
1 srv1
2 srv2 , srv12
3 srv1 , srv10
4 srv8
5 srv3 , srv4
6 srv1 , srv7
7 srv5
8 srv9
使用以下代码
merge = pandas.merge(df1,df2,on="ID",how="left")
merge["word"] = merge[word_x] + " , " + merge["word_y"]
我得到:
ID word
1 nan
2 srv2 , srv12
3 srv1 , srv10
4 nan
5 srv3 , srv4
6 srv1 , srv7
7 nan
8 nan
这不是正确的解决方案。
答案 0 :(得分:5)
即使na_rep
中的源列之一,也可以使用Series.str.cat
和word
选项填充nan
列,然后使用str.strip
修剪单词之间的前导/后缀' , '
。
m['word'] = m['word_x'].str.cat(m['word_y'], sep=' , ', na_rep='').str.strip(' , ')
返回
ID word_x word_y word
0 1 srv1 NaN srv1
1 2 srv2 srv12 srv2 , srv12
2 3 srv1 srv10 srv1 , srv10
3 4 NaN srv8 srv8
4 5 srv3 srv4 srv3 , srv4
5 6 srv1 srv7 srv1 , srv7
6 7 srv5 NaN srv5
7 8 NaN srv9 srv9
答案 1 :(得分:1)
您可以使用np.select
选择现有值或串联值。
尝试一下:
import pandas as pd
import numpy as np
from io import StringIO
df1 = pd.read_csv(StringIO("""
ID word
1 srv1
2 srv2
3 srv1
4 nan
5 srv3
6 srv1
7 srv5
8 nan"""), sep=r"\s+")
df2 = pd.read_csv(StringIO("""
ID word
1 nan
2 srv12
3 srv10
4 srv8
5 srv4
6 srv7
7 nan
8 srv9"""), sep=r"\s+")
conditions = [(~df1["word"].isna()) & df2["word"].isna(), df1["word"].isna() & (~df2["word"].isna()), (~df1["word"].isna()) & (~df2["word"].isna())]
choices = [df1["word"], df2["word"], df1["word"] + "," + df2["word"]]
df1["word"] = np.select(conditions,choices)
print(df1)
输出:
ID word
0 1 srv1
1 2 srv2,srv12
2 3 srv1,srv10
3 4 srv8
4 5 srv3,srv4
5 6 srv1,srv7
6 7 srv5
7 8 srv9
答案 2 :(得分:0)
根据我认为您想做的事,我会首先去除那些nan
:
df_1.fillna(value="")
df_2.fillna(value="")
然后我将再次尝试合并,看看您是否得到了想要的东西。