Python 通过数据框连接两个同名列

Python 通过数据框连接两个同名列,python,pandas,Python,Pandas,我是熊猫的初学者。我有一个输入,比如 num. first second x x.1 x.2 x.3 last 1 ah ro hg rl ew wk o2 2 as ht hf cd ek qi 4j 3 uy rf kh we ls qj ke 输出将是 num. first second x last 1 ah ro hg,

我是熊猫的初学者。我有一个输入,比如

num. first second  x    x.1  x.2 x.3  last
1     ah     ro    hg   rl   ew  wk   o2
2     as     ht    hf   cd   ek  qi   4j
3     uy     rf    kh   we   ls  qj   ke
输出将是

num. first second    x          last
1     ah     ro    hg,rl,ew,wk   o2
2     as     ht    hf,cd,ek,qi   4j
3     uy     rf    kh,we,ls,qj   ke
试试这个:

col_x = [*filter(lambda x: x.startswith('x.'), df.columns)]
df['x'] = df[col_x].apply(lambda row: ','.join(row), axis=1)
df = df.drop(col_x, axis=1)
试试这个:

col_x = [*filter(lambda x: x.startswith('x.'), df.columns)]
df['x'] = df[col_x].apply(lambda row: ','.join(row), axis=1)
df = df.drop(col_x, axis=1)
这里有一个解决方案:

cols = df.filter(regex='^x').columns
df['x'] = df[cols].agg(','.join, axis=1)
df = df.drop(cols, axis=1)
输出:

   num. first second last         x
0     1    ah     ro   o2  rl,ew,wk
1     2    as     ht   4j  cd,ek,qi
2     3    uy     rf   ke  we,ls,qj
这里有一个解决方案:

cols = df.filter(regex='^x').columns
df['x'] = df[cols].agg(','.join, axis=1)
df = df.drop(cols, axis=1)
输出:

   num. first second last         x
0     1    ah     ro   o2  rl,ew,wk
1     2    as     ht   4j  cd,ek,qi
2     3    uy     rf   ke  we,ls,qj
你可以试试这个-

df['x'] = df['x.1'] + ',' + df['x.2'] + ',' + df['x.3']
df = df.drop(['x.1', 'x.2', 'x.3'], axis=1)
你可以试试这个-

df['x'] = df['x.1'] + ',' + df['x.2'] + ',' + df['x.3']
df = df.drop(['x.1', 'x.2', 'x.3'], axis=1)
尝试:

df[“x”]=df[“x.1”].cat([df[“x.2”]、df[“x.3”]、sep=“,”)
#然后要删除所有x.n:
测向=测向下降([“x.1”、“x.2”、“x.3”],轴=1)
试试:

df[“x”]=df[“x.1”].cat([df[“x.2”]、df[“x.3”]、sep=“,”)
#然后要删除所有x.n:
测向=测向下降([“x.1”、“x.2”、“x.3”],轴=1)
很容易做到:

l1 = ['hg', 'rl', 'ew', 'wk']
','.join(l1) # hg,rl,ew,wk
然后我们需要对每行的x~x.3列执行此操作,因此我们使用

然后我们得到一个新的pd.系列,这是您所期望的,只需将其分配给前一个数据帧即可。

很容易:

l1 = ['hg', 'rl', 'ew', 'wk']
','.join(l1) # hg,rl,ew,wk
然后我们需要对每行的x~x.3列执行此操作,因此我们使用


然后我们得到一个新的pd.Series,它是您所期望的,只需将它分配给前一个数据帧。

TypeError:('sequence item 1:expected str instance,float found','Occurd at index 0')它给出了这个errorTypeError:('sequence item 1:expected str instance,float found','Occurd at index 0'))它给出了这个错误。你能澄清问题的具体内容吗?请看,。你能澄清到底是什么问题吗?请看,。虽然这可能是一个有效的答案,但提供一些解释是很好的。虽然这可能是一个有效的答案,但提供一些解释是很好的。我建议df['x']=df['x'].str.cat(df[cols],sep=','),因为它将x的值引入最终结果,并将输出匹配为OP postedi'd建议df['x']=df['x'])。str.cat(df[cols],sep=','),因为它将x的值引入最终结果,并将输出匹配为OP posted