亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python:基于列與列表連接列

Python:基于列與列表連接列

夢里花落0921 2022-07-26 10:54:31
我有一個DataFrame如下:df      A    B     C    D    E    key0  test    Z  10.0    a    a  101111  test    A  10.0    a    a  101112  test    x   2.0    a    b  110103  test    5  12.0    b    b  101004  test    x   5.0    c    b  110005  test    2  14.0    g    c  10111我需要得到的是將所有字符串相應地連接到key列:keyat position[0]是 for col A,keyat position[1]是 forcol B等等...每個1in 用于拍攝,每個0用于跳過列結果應如下所示:      A    B     C    D    E    key     key_val0  test    Z  10.0    a    a  10111  test10.0aa1  test    A  10.0    a    a  10111  test10.0aa2  test    x   2.0    a    b  11010      testxa3  test    5  12.0    b    b  10100    test12.04  test    x   5.0    c    b  11000       testx5  test    2  14.0    g    c  10111  test14.0gc到目前為止我所做的 - 我創建了 key_list 列:df['key_list'] = df['key'].apply(lambda x: list(str(x)))df      A  B     C  D  E    key         key_list0  test  Z  10.0  a  a  10111  [1, 0, 1, 1, 1]1  test  A  10.0  a  a  10111  [1, 0, 1, 1, 1]2  test  x   2.0  a  b  11010  [1, 1, 0, 1, 0]3  test  5  12.0  b  b  10100  [1, 0, 1, 0, 0]4  test  x   5.0  c  b  11000  [1, 1, 0, 0, 0]5  test  2  14.0  g  c  10111  [1, 0, 1, 1, 1]下一步我已經嘗試過了(我想乘以 1 或 0 來包含或排除字符串):df.apply((df['A'].astype(str) * df['key_list'][0]) +         (df['B'].astype(str) * df['key_list'][1]) +         (df['C'].astype(str) * df['key_list'][2]) +         (df['D'].astype(str) * df['key_list'][3]) +         (df['E'].astype(str) * df['key_list'][4]), axis=1)但這似乎是錯誤的想法:ValueError: operands could not be broadcast together with shapes (6,) (5,)。我遵循字符串連接的常見做法,只是額外的步驟:df['A'].astype(str) + df['B'].astype(str) + df['C'].astype(str) + df['D'].astype(str) + df['E'].astype(str)
查看完整描述

1 回答

?
鴻蒙傳說

TA貢獻1865條經驗 獲得超7個贊

想法是將key列轉換為掩碼,然后用空字符串替換不匹配DataFrame.where并求和join:


c = ['A','B','C','D','E']


L = [list(str(x)) for x in df['key']]

m = pd.DataFrame(L, columns=c, index=df.index).fillna(0).astype(int).astype(bool)

print (m)

      A      B      C      D      E

0  True  False   True   True   True

1  True  False   True   True   True

2  True   True  False   True  False

3  True  False   True  False  False

4  True   True  False  False  False

5  True  False   True   True   True


df['key_val'] = df[c].where(m, '').astype(str).sum(axis=1)

print (df)

      A  B     C  D  E    key     key_val

0  test  Z  10.0  a  a  10111  test10.0aa

1  test  A  10.0  a  a  10111  test10.0aa

2  test  x   2.0  a  b  11010      testxa

3  test  5  12.0  b  b  10100    test12.0

4  test  x   5.0  c  b  11000       testx

5  test  2  14.0  g  c  10111  test14.0gc


查看完整回答
反對 回復 2022-07-26
  • 1 回答
  • 0 關注
  • 99 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號