【问题标题】:Python Pandas, Dataframe and reading from excel filePython Pandas、Dataframe 和从 excel 文件中读取
【发布时间】:2021-10-08 16:41:01
【问题描述】:

如何合并从 Excel 文件中读取的具有相似值的数据?

import pandas as pd
import numpy as np
df = pd.read_excel("testfile.xlsx")
print(df)

文件示例:testdata.xlsx

Identifier   Dates
123456       1/1/2021
789101       2/2/2021
221342       3/3/2021
231344       1/1/2021
134562       2/2/2021
135650       2/2/2021
135677       2/2/2021
2246         1/1/2021
24682        3/3/2021
245684       1/1/2021

想要的输出数据(合并某个日期对应的数据):

2/2/2021   789101 134562 135650 135677  
1/1/2021   245684   2246 231344
3/3/2021   24682  221342

【问题讨论】:

  • 你想groupby
  • 您希望每个字段都有单独的列吗? (如果是这样,这是一个支点)
  • 不,我想将所有具有相同日期的数据添加到一行中。例如,对于日期 2/2/2021,它有多个 Identifiers,我希望 2/2/2021 的所有标识符在一行中等等。

标签: python pandas dataframe


【解决方案1】:

这能解决您的问题吗?

df.groupby(['Dates'])['Identifier'].apply(list)
Dates
1/1/2021      [123456, 231344, 2246, 245684]
2/2/2021    [789101, 134562, 135650, 135677]
3/3/2021                     [221342, 24682]
Name: Identifier, dtype: object

如果您不希望将其作为列表,而是作为带有空格分隔的字符串,正如您在问题中指出的那样,那么试试这个 -

df.astype({'Identifier':str}).groupby(['Dates'])['Identifier'].apply(' '.join)
Dates
1/1/2021      123456 231344 2246 245684
2/2/2021    789101 134562 135650 135677
3/3/2021                   221342 24682
Name: Identifier, dtype: object

【讨论】:

  • 我想将所有具有相同日期的数据添加到一行中。例如,对于日期 2/2/2021,它有多个标识符,我希望 2/2/2021 的所有标识符在一行中,依此类推。 ——
  • 您有机会尝试上述方法吗?我相信它可以解决您在上面的评论中提到的问题。
  • 我做了,但没用
  • 您能否详细说明为什么它不起作用?你得到什么输出?您是否尝试使用您自己发布的虚拟数据运行它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-14
  • 2021-11-10
  • 2019-06-08
  • 2018-05-15
  • 2013-06-08
相关资源
最近更新 更多