簡體   English   中英

如何使用現有列名稱和值在Pandas數據框中創建列表的新列?

[英]How to create new column of lists in Pandas dataframe using existing column names and values?

我目前正在使用R進行數據科學,並且正在學習Python和Pandas來擴展我的工具箱。 我想使用現有的列名和值在Pandas數據框中創建一個新的列表列。

對於以下Pandas數據框:

  test1  test2  test3
1      0      1      1
2      0      1      0
3      1      1      1
4      1      0      0
5      0      0      0

一個新列將為每行包含一個列表,該列表將列名稱取為“ 1”的任何位置,剝去“ test”前綴,並使用“-”分隔符將列表連接起來。

   test1  test2  test3  combo
0      0      1      1    2-3
1      0      1      0      2
2      1      1      1  1-2-3
3      1      0      0      1
4      0      0      0  

我可以使用以下代碼在R和data.table中創建列:

df [, combo := apply (df == 1, 1, function(x) {
   paste (gsub("test", "", names(which(x))), collapse = "-")
}
)]

這是我來熊貓市最近的地方:

def test(x):
    paste(loc[x])

df['combo'] = df.apply(test, df == 1, axis = 1)

TypeError: apply() got multiple values for argument 'axis'

我在正確的道路上嗎?

df['combo'] = df.apply(lambda x: '-'.join(list(x[x == 1].index)).replace('test', ''), axis=1)

產生以下輸出:

In [8]: df
Out[8]:
   test1  test2  test3  combo
0      0      1      1    2-3
1      0      1      0      2
2      1      1      1  1-2-3
3      1      0      0      1
4      0      0      0

函數lambda x: '-'.join(list(x[x == 1].index)).replace('test', '')選擇等於1的系列元素的索引。行的索引是列名test1, test2, test3 ,因此在加入列表之后,有必要用'test'替換結果字符串中的'test' ''

並且我們需要沿行應用此函數,因此我們傳遞axis=1 默認axis=0沿列應用該功能。

您可以先重命名列,然后使用Apply提取列名,然后將它們聯接。

df['combo'] = (
   df.rename(columns=lambda x: x.replace('test',''))
   .astype(bool)
   .apply(lambda x: '-'.join(x.loc[x].index), axis=1)
)

df
Out[15]: 
   test1  test2  test3  combo
1      0      1      1    2-3
2      0      1      0      2
3      1      1      1  1-2-3
4      1      0      0      1
5      0      0      0       

暫無
暫無

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

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