【问题标题】:DataFrame dynamic columns from embedded lists in dataFrame数据帧中嵌入列表的数据帧动态列
【发布时间】:2017-12-08 21:52:24
【问题描述】:

好的,所以我是 Python 的相对菜鸟。我需要对以下数据框进行转换

bd,日期

[[None]], 2017-11-01 09:00:00

[[Sulphur], [Green Tea]], 2017-11-02 09:00:00 

[[Green Tea], [Jasmine]], 2017-11-03 09:00:00 

.....

转化为

日期、无、硫磺、绿茶、茉莉花...

2017-11-01 09:00:00, 1, 0, 0, 0...

2017-11-02 09:00:00, 0, 1, 1, 0...

2017-11-03 09:00:00, 0, 0, 1, 1...

BD列内嵌列表中的项目是动态的,不能是新dataFrame中的预定义列。

我通过另一篇有用的帖子Create new columns in pandas from python nested lists 尝试了以下内容,但无法成功调整

suppDF1 = suppDF.bd.apply(lambda x: pd.Series(1, x)).fillna(0).astype(int)

使用上面的代码,我只看到 5 列不正确的 1,所以我显然超出了我的理解范围。

更新

我尝试了 Max 的建议,但我想我在尝试使用 pivot 时可能有一些错误:

suppDF1 = suppDF.pivot(index="date", columns="bd")["bd"]

我收到以下错误

unhashable type: 'list'

【问题讨论】:

  • 你试过pivot吗?
  • 感谢 Max 的建议 - 我在我的 df 上尝试过,但它给了我这个错误:unhashable type: 'list' 我使用了以下代码:suppDF1 = suppDF.pivot(index="date" , columns="bd")["bd"]
  • 等等,suppDF1 = suppDF.pivot(index="date", columns="bd") 会抛出错误,还是在最后添加索引["bd"] 时发生错误?
  • 无论哪种方式我都会得到相同的错误 - 即使我最后删除 ["bd"] ,错误也不会改变。这确实让我想知道,我的数据可能没有唯一的日期。这是对枢轴的要求吗?如果是这样,如果需要唯一性,我是否应该尝试添加索引列
  • 对不起,我只想指出,BD 列的内容是一个列表,这可能意味着我需要在尝试枢轴之前以某种方式解压。

标签: python list pandas dataframe


【解决方案1】:

我确信有更优雅、更实用、更 Pythonic 的方法可以做到这一点……我很想知道它们是什么。

import numpy as np
import pandas as pd

# define dataframe
df = pd.DataFrame(columns = ['bd', 'date'])
df.loc[0, 'bd'] = [[None]]
df.loc[0, 'date'] = '2017-11-01 09:00:00'
df.loc[1, 'bd'] = [['Sulphur'], ['Green Tea']]
df.loc[1, 'date'] = '2017-11-02 09:00:00'
df.loc[2, 'bd'] = [['Green Tea'], ['Jasmine']]
df.loc[2, 'date'] = '2017-11-03 09:00:00'
print(df)

# set the index
df.set_index('date', inplace = True)

# df['bd'] contains doubly nested lists
# for item in column, for list in item, for string in list, add string to list
cols = []
for ls2 in df['bd']:
    for ls1 in ls2:
        for string in ls1:
            if string not in cols:
                cols.append(string)

# make a column for every string in df['bd']
for tea in cols:
    df[tea] = 0

# manual one-hot encoding; couldn't get pd.get_dummies() to work
for row in df.iterrows():
    for ls in row[1][0]:
        for el in ls:
            if el in df.columns:
                df.loc[row[0], el] = 1
df.drop('bd', axis = 1, inplace = True)
df.fillna(0)

我花了一些时间在这上面;以下是一些不完全奏效的东西:

我无法让这个递归函数为我工作(怪我,不是函数)... Flatten (an irregular) list of lists

我试过get_dummies,但它不能散列一个列表,更不用说一个双重嵌套的列表...... https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html

我试过旋转和pivot_table... https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html

我尝试将列表转换为字符串,但最终也陷入了死胡同…… Converting a Panda DF List into a string

【讨论】:

  • 泰埃文。我想可能有一种更优雅的方式来做到这一点..但我真的很感谢你的回答。它可以工作..因为这可能是我需要的许多齿轮之一..我很高兴用这种方法在我的项目上取得进展。
猜你喜欢
  • 2021-07-25
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 2017-05-26
  • 1970-01-01
  • 2010-12-11
  • 2021-08-18
  • 1970-01-01
相关资源
最近更新 更多