簡體   English   中英

用每行中最長的字符串替換 Pandas Dataframe 中的列

[英]Replace columns in Pandas Dataframe with the longest String in each Row

我有一個 Dataframe,其中有一列包含玩家姓名。 使用以下代碼,我將其拆分為您在圖片中看到的 Dataframe:

df = df.name.str.split(expand=True)

數據框 df

現在我想在每一行中找到最長的字符串並將其放入一個新列中。 我希望我已經清楚地解釋了我的問題。 謝謝你的幫助:)

您可以將 function 應用於行軸以刪除 nan 值,然后將len傳遞給key參數以獲得最大值:

>>> df['new_column']=df.apply(lambda x: max(x.dropna() ,key=len), axis=1)

您可以stack並獲得每個級別最大長度的行:

s = df.stack()
df['new'] = s.loc[s.str.len().groupby(level=0).idxmax()].droplevel(1)

例子:

     0    1     2   3   new
0  ABC    D  EFGH      EFGH
1    A  BCD   EFG   H   BCD
2    A   BC   DEF  GH   DEF

使用的輸入:

df = pd.DataFrame([['ABC', 'D', 'EFGH', ''],
                   ['A', 'BCD', 'EFG', 'H'],
                   ['A', 'BC', 'DEF', 'GH'],
                  ])

暫無
暫無

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

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