gpt4 book ai didi

python - 您如何使用字符串列表作为值来对列进行一次热编码?

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:20 26 4
gpt4 key购买 nike

我基本上是在尝试用这样的值对一列进行热编码:

  tickers
1 [DIS]
2 [AAPL,AMZN,BABA,BAY]
3 [MCDO,PEP]
4 [ABT,ADBE,AMGN,CVS]
5 [ABT,CVS,DIS,ECL,EMR,FAST,GE,GOOGL]
...

首先我得到了所有的代码集(大约有 467 个代码):

all_tickers = list()
for tickers in df.tickers:
for ticker in tickers:
all_tickers.append(ticker)
all_tickers = set(all_tickers)

然后我用这种方式实现了一个热编码:

for i in range(len(df.index)):
for ticker in all_tickers:
if ticker in df.iloc[i]['tickers']:
df.at[i+1, ticker] = 1
else:
df.at[i+1, ticker] = 0

问题是脚本在处理大约 5000 多行时运行得非常慢。如何改进我的算法?

最佳答案

我想你需要str.joinstr.get_dummies :

df = df['tickers'].str.join('|').str.get_dummies()

或者:

from sklearn.preprocessing import MultiLabelBinarizer

mlb = MultiLabelBinarizer()

df = pd.DataFrame(mlb.fit_transform(df['tickers']),columns=mlb.classes_, index=df.index)
print (df)
AAPL ABT ADBE AMGN AMZN BABA BAY CVS DIS ECL EMR FAST GE \
1 0 0 0 0 0 0 0 0 1 0 0 0 0
2 1 0 0 0 1 1 1 0 0 0 0 0 0
3 0 0 0 0 0 0 0 0 0 0 0 0 0
4 0 1 1 1 0 0 0 1 0 0 0 0 0
5 0 1 0 0 0 0 0 1 1 1 1 1 1

GOOGL MCDO PEP
1 0 0 0
2 0 0 0
3 0 1 1
4 0 0 0
5 1 0 0

关于python - 您如何使用字符串列表作为值来对列进行一次热编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47786822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com