簡體   English   中英

Pandas將選定的列合並為1

[英]Pandas merging selected columns into 1

我有這樣的df:

ID1 ID2 Day Text1 Text2 Text3 ....
111 A   1   a     b     c
222 B   2   i     j     k
333 C   3   x     y     z

我的目標是創建一個包含Text1,Text2,Text3等所有值的新列。

ID1 ID2 Day Text1 Text2 Text3 ....  Text
111 A   1   a     b     c           a, b, c...
222 B   2                          
333 C   3   x           y           x, y, .... 

我試過了:

list(zip(df.Text1,df.Text2,df.Text3,...)): 

這有效,但格式不可取。

和:

df.apply(lambda x: ', '.join(x.astype(str)), axis=1): 

這給出了所需的格式,但答案將包含所有字段。

這最好的方法是什么? 非常感謝!

矢量化解決方案:

In [65]: df['Text'] = df.filter(regex='^Text\d+').add(', ').sum(1).str.rstrip(', ')

In [66]: df
Out[66]:
   ID1 ID2  Day Text1 Text2 Text3     Text
0  111   A    1     a     b     c  a, b, c
1  222   B    2     i     j     k  i, j, k
2  333   C    3     x     y     z  x, y, z

你的代碼非常接近。 您只需要在df[text_cols]上使用apply ,其中text_cols是要合並到新列的列的列表。

df['Text'] = df[text_cols].apply(lambda x: ''.join(x), axis=1)

還有一個矢量化join

>>> df['Text'] = df.filter(regex='^Text\d+').sum(1).str.join(', ')
>>> df
   ID1 ID2  Day Text1 Text2 Text3     Text
0  111   A    1     a     b     c  a, b, c
1  222   B    2     i     j     k  i, j, k
2  333   C    3     x     y     z  x, y, z

其他解決方案很棒,我想提供一個使用cat()函數的答案。

df['text'] = df[0].str.cat([df[i] for i in df.columns[1:]],sep=',')

希望能幫助到你 : )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM