简体   繁体   English

想要从 pandas/python 中的数据帧创建一个像数据帧这样的稀疏矩阵

[英]Want to create a sparse matrix like dataframe from a dataframe in pandas/python

I have a data frame like this我有一个这样的数据框输入数据

I want to convert it to something like this,note the ds is the day someone visited,and will have values from 0 to 31, for the days not visited it will show 0, and for the days visited it will show 1. It's kinda like sparse matrix,can someone help我想把它转换成这样,注意 ds 是有人访问的日期,值从 0 到 31,未访问的天数显示 0,访问的天数显示 1。有点像像稀疏矩阵,有人可以帮忙吗想要的结果

Adding to the solution from @sim.从@sim 添加到解决方案。 By using the parameter columns, one can avoid the join.通过使用参数列,可以避免连接。 the sparse=True parameter will return a sparse matrix. sparse=True 参数将返回一个稀疏矩阵。 sparse=False will return a dense matrix. sparse=False 将返回一个密集矩阵。

header = ["ds", "buyer_id", "email_address"]
data = [[23, 305, "fatin1bd@gmail.com"],
        [22, 307, "shovonbad@gmail.com"],
        [25, 411, "raisulk@gmail.com"],
        [22, 588, "saiful.sdp@hotmail.com"],
        [24, 664, "osman.dhk@gmail.com"]]
df = pd.DataFrame(data, columns=header)
df=pd.get_dummies(df,columns=['ds'],sparse=True)

If you use sparse=True, the result can be converted back to dense using sparse.to_dense() on the specific column.如果您使用 sparse=True,则可以在特定列上使用 sparse.to_dense() 将结果转换回密集。 For more details refer to User Guide有关更多详细信息,请参阅用户指南

ds_cols=[col for col in df.columns if col.startswith('ds_')]
df=pd.concat([df[['buyer_id',"email_address"]],
                           df[ds_cols].sparse.to_dense()],axis=1)

Update: pd.get_dummies now accepts sparse=True to create a SparseArray output.更新: pd.get_dummies现在接受sparse=True来创建SparseArray输出。

pd.get_dummies(s: pd.Series) can be used to create a one-hot encoding like such: pd.get_dummies(s: pd.Series)可用于创建像这样的 one-hot 编码:

header = ["ds", "buyer_id", "email_address"]
data = [[23, 305, "fatin1bd@gmail.com"],
        [22, 307, "shovonbad@gmail.com"],
        [25, 411, "raisulk@gmail.com"],
        [22, 588, "saiful.sdp@hotmail.com"],
        [24, 664, "osman.dhk@gmail.com"]]
df = pd.DataFrame(data, columns=header)
df.join(pd.get_dummies(df["ds"]))

output:输出:

ds  buyer_id    email_address   22  23  24  25
0   23  305     fatin1bd@gmail.com  0   1   0   0
1   22  307     shovonbad@gmail.com     1   0   0   0
2   25  411     raisulk@gmail.com   0   0   0   1
3   22  588     saiful.sdp@hotmail.com  1   0   0   0
4   24  664     osman.dhk@gmail.com     0   0   1   0

Just for added clarification: The resulting dataframe is still stored in a dense format.仅作补充说明:生成的数据帧仍以密集格式存储。 You could use scipy.sparse matrix formats to store it in a true sparse format.您可以使用scipy.sparse矩阵格式以真正的稀疏格式存储它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM