【问题标题】:How can I join 2 rows in a dataframe into 1 row in a new one?如何将数据框中的 2 行加入新的 1 行?
【发布时间】:2015-04-12 19:38:14
【问题描述】:

我正在过滤格式化为 Excel 文件的外部数据源。我无法更改文件的生成方式。我需要过滤掉无用的行并将成对的行合并为一个。到目前为止,我的过程适用于过滤,但不适用于将两个连续行中的相关数据合并为一行。

数据帧没有为 stackoverflow 很好地转换,但我在下面手动调整了它们。

数据转换

将下载内容转换为有用的格式

import pandas as pd
from pandas          import DataFrame
from pandas.io.excel import read_excel
cpath = os.path.join (download_path, classes_report)
print (pd.__version__)

df = pd.read_excel (cpath, sheetname=0, header=None)
df.to_string()

0.14.1

0 1 2 3 4 5 0 Session: 2014-2015 NaN NaN NaN NaN NaN 1 Class Information Age Enrolled Key Room NaN 2 Math 10 12 / 18 03396 110 09:00:00 3 Teacher: Joe M Teacher NaN NaN NaN NaN 4 NaN NaN NaN NaN NaN NaN 5 NaN NaN NaN NaN 6 NaN NaN NaN NaN 7 NaN NaN NaN NaN NaN NaN 8 NaN NaN NaN NaN NaN NaN 9 Number of Classes: 1 Number of Students: 12 / 18 NaN NaN NaN NaN 10 Class Information Ages Enrolled Key Room NaN 11 Art 18 - 80 3 / 24 03330 110 10:00:00 12 Teacher: John A Instructor NaN NaN NaN NaN 13 NaN NaN NaN NaN NaN NaN 14 NaN NaN NaN NaN 15 NaN NaN NaN NaN

# Eliminate any rows where first column is NaN, contains 'Number of Classes', 'Class Information'
# or is blank
# The 5th column is tuition.

cf = df[df[0].notnull ()][1:]
cf = cf [~cf[0].str.contains ('Number of Classes')]
bf = cf[~cf[0].isin ([' ', 'Class Information'])]
bf.to_string()

0 1 2 3 4 5 2 Math 10 12 / 18 03396 110 09:00:00 3 Teacher: Joe M Teacher NaN NaN NaN NaN 11 Art 18 - 80 3 / 24 03330 110 10:00:00 12 Teacher: John A Instructor NaN NaN NaN NaN

left  = DataFrame(bf.values [::2], index=bf.index[::2])
right = DataFrame(bf.values [1::2], index=bf.index[1::2])
pd.concat([left, right], axis=1).to_string ()

0 1 2 3 4 5 0 1 2 3 4 5 2 Math 10 12 / 18 03396 110 09:00:00 NaN NaN NaN NaN NaN NaN 3 NaN NaN NaN NaN NaN NaN Teacher: Joe M Teacher NaN NaN NaN NaN 11 Art 18 - 80 3 / 24 03330 110 10:00:00 NaN NaN NaN NaN NaN NaN 12 NaN NaN NaN NaN NaN NaN Teacher: John A Instructor NaN NaN NaN NaN

这里的目标是让“Math”行的最后五列包含以“Teacher:”开头的列,对于“Art”行也是如此,留下两行而不是四行的数据框。

【问题讨论】:

  • 试试pd.concat([left, right], axis=1, ignore_index=True)
  • 您明确设置了右侧 df 的索引,如果它的行数相同并且您希望它们对齐,为什么不使用与左侧相同的索引:right = DataFrame(bf.values [1::2], index=left.index)?那么 concat 会产生你不想要的东西吗?
  • @EdChum - 这行得通。如果您将其写为答案,我可以将其标记为已接受。

标签: python pandas dataframe merging-data


【解决方案1】:

您尝试concat 按索引对齐 2 个 df,从而产生一个 4 行而不是 2 行的脱节 df:

right = DataFrame(bf.values [1::2], index=bf.index[1::2])

上面使用来自您的 df 的值创建了一个新的 df,但您也获取了索引值,因为左右 df 具有相同的行数,并且您希望按列连接它们以便索引对齐,然后您可以使用左侧 df 的相同索引:

right = DataFrame(bf.values [1::2], index=left.index)

这将产生所需的串联df。

【讨论】:

    猜你喜欢
    • 2021-02-10
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 2018-09-29
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    相关资源
    最近更新 更多