【问题标题】:how to compare the value in different size of each Dataframe and returning String如何比较每个数据框不同大小的值并返回字符串
【发布时间】:2020-05-06 15:32:56
【问题描述】:

假设我要比较的 5 个数据帧是

ID_DocAll ID_Doc1 ID_Doc2 ID_Doc3 ID_Doc4
  10         21     21      10      7
  21         7      10      21
  32                32      54
  54                 7    
   7                

并将预期结果视为

ID_DocAll 
10        ID_Doc2, ID_Doc3
21        ID_Doc1, ID_Doc2, ID_Doc3
32        ID_Doc2
54        ID_Doc3
7         ID_Doc1, ID_Doc2, ID_Doc4

有什么建议吗?我关注了这个帖子Comparing Boolean Values of Pandas Dataframes- Returning String

但我对数据框的大小有疑问,即使我用 0 填充 NaN 使其相等,也无法调整它们的大小。

【问题讨论】:

  • 输入数据中的空值是缺失值还是空字符串?
  • 它是空字符串

标签: python pandas


【解决方案1】:

如果输入数据中的空值是空字符串并且ID_DocAll 列具有唯一值,则使用:

首先删除 ID_DocAll 列以处理由 DataFrame.melt 处理的所有其他列,删除带有空字符串的行并聚合 join 每个值

s = (df.drop('ID_DocAll', axis=1)
       .melt(var_name='ID_DocAll')
       .loc[lambda x: x['value'].ne('')]
       .groupby('value')['ID_DocAll']
       .agg(','.join))

print (s)
value
7.0     ID_Doc1,ID_Doc2,ID_Doc4
10.0            ID_Doc2,ID_Doc3
21.0    ID_Doc1,ID_Doc2,ID_Doc3
32.0                    ID_Doc2
54.0                    ID_Doc3
Name: ID_DocAll, dtype: object

最后一个变更单使用Series.reindex(仅s索引中的必要数值和ID_DocAll列中的数字):

s1 = s.reindex(df['ID_DocAll'])
print (s1)

ID_DocAll
10            ID_Doc2,ID_Doc3
21    ID_Doc1,ID_Doc2,ID_Doc3
32                    ID_Doc2
54                    ID_Doc3
7     ID_Doc1,ID_Doc2,ID_Doc4
Name: ID_DocAll, dtype: object

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多