【问题标题】:Store previous rows details in a list of dictionary in Dataframe将前行详细信息存储在 Dataframe 中的字典列表中
【发布时间】:2018-08-02 05:14:48
【问题描述】:

将先前行的详细信息存储在 Dataframe 中的字典列表中。 DataFrame 就像

df:
Rows    Alphabet    Count
r1      a           1
r2      a           2
r3      b           1
r4      a           3
r5      b           2

有没有可能输出应该是这样的

df:
Rows    Alphabet    Count   countDetails
r1      a           1       [{id:a,count:1}]
r2      a           2       [{id:a,count:2}]
r3      b           1       [{id:a,count:2},{id:b,count:1}]
r4      a           3       [{id:a,count:3},{id:b,count:1}]
r5      b           2       [{id:a,count:3},{id:b,count:2}]

它应该存储到达该行的字母数量和每个字母的数量。 就像直到 r3 只有 'a' 存在,而在 r3 字母表中,'b' 出现了,所以它应该存储 'a' 和 'b' 的计数

【问题讨论】:

  • 字母列的可能值是多少?整个 a-z?
  • 是的,整个 a-z。它只是一个例子,它可能是 1-100 或 1-1000 这样的任何东西。可以这样存储。
  • 为什么需要这样做?

标签: python python-2.7 pandas dataframe


【解决方案1】:

试试这个:

df['countDetails'] = ''

count_dict = {}

for index, row in df.iterrows():
    count_dict.setdefault(row['Alphabets'], 0)
    count_dict[row['Alphabets']] = row['Count']
    k= map(lambda x:{'id':x,'count':count_dict[x]}, count_dict)

    df.at[ index, 'countDetails'] = k

【讨论】:

  • 我已经稍微修改了解决方案,如果你有时间请看一下。
  • 欢迎老兄!如果答案解决了问题,请将其标记为“正确答案”!您可以查看here。只是建议您似乎是新用户。
  • @AbhijitGhate:太好了!!您可以将第 9-14 行替换为 k= map(lambda x:{'id':x, 'count':count_dict[x]}, count_dict)
  • @AmarKamthe 是的,这更整洁
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 2014-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多