python - 元组列表到二进制表中?

标签 python list pandas dataframe data-structures

我有一个 Python 中的事务/元组列表,其中包含不同数量或元素,如下所示:

lst = [('apple','banana','carrots'),('apple',),('banana','carrots',)]

我想以表格形式(最好是 pd.DataFrame)存储这个列表,例如:

   apple  banana  carrots
0      1       1        1
1      1       0        0
2      0       1        1

但是如果尝试直接使用 pd.DataFrame 进行转换,我会得到他的:

pd.DataFrame(lst)
        0        1        2
0   apple   banana  carrots
1   apple     None     None
2  banana  carrots     None

如何将这种类型的列表转换为二进制表?

最佳答案

如果您在列上使用 value_counts 就非常简单,即

pd.DataFrame(lst).apply(pd.value_counts,1).fillna(0)

    apple  banana  carrots
0    1.0     1.0      1.0
1    1.0     0.0      0.0
2    0.0     1.0      1.0

关于python - 元组列表到二进制表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47783833/

相关文章:

python - 如何对条形图的值进行分组和绘制 matplotlib

python - 在 Tkinter Canvas 上旋转一个正方形

python - Pandas 数据帧到内存中的 Parquet 缓冲区

python - 所以我想用 Python 制作一个时钟来显示上午和下午。和下午

python - 使用继承的 python optparse 选项生成进程

python - 程序解析错误表

java - 如何一次删除不同的可更新记录?

python - 检索 Pandas 数据帧行,其列(一)值连续等于列表的值

python - 找到每个 pandas 组最接近的时间值

pandas - 如何使用标称值绘制 Pandas 的直方图?