【问题标题】:How to combine some rows into a single row如何将一些行合并为一行
【发布时间】:2020-12-23 10:35:42
【问题描述】:

抱歉,我应该删除旧问题并创建新问题。 我有一个包含两列的数据框。 df 如下所示:

                     Word   Tag
0                    Asam   O
1               instruksi   O
2                       -   O
3               instruksi   X
4                  bahasa   Y
5               Instruksi   P
6                       -   O
7               instruksi   O
8                  sebuah   Q
9                  satuan   K
10                      -   L
11                 satuan   O
12                   meja   W
13                   Tiap   Q
14                      -   O
15                   tiap   O
16               karakter   P
17                      -   O
18                     ke   O
19                      -   O
20               karakter   O

我想将一些包含破折号- 的行合并为一行。所以输出应该如下:

                     Word   Tag
0                    Asam   O
1     instruksi-instruksi   O
2                  bahasa   Y
3     Instruksi-instruksi   P
4                  sebuah   Q
5           satuan-satuan   K
6                    meja   W
7               Tiap-tiap   Q
8    karakter-ke-karakter   P

有什么想法吗?提前致谢。我尝试了 Jacob K 的答案,它有效,然后我在我的数据集中发现,两者之间有不止一个 - 行。我已经放了预期的输出,比如索引号 8

Jacob K 的解决方案:

# Import packages
import pandas as pd
import numpy as np

# Get 'Word' and 'Tag' columns as numpy arrays (for easy indexing)
words = df.Word.to_numpy()
tags = df.Tag.to_numpy()

# Create empty lists for new colums in output dataframe
newWords = []
newTags = []

# Use while (rather than for loop) since index i can change dynamically
i = 0                             # To not cause any issues with i-1 index
while (i < words.shape[0] - 1):
    if (words[i] == "-"):
        # Concatenate the strings above and below the "-"
        newWords.append(words[i-1] + "-" + words[i+1])
        newTags.append(tags[i-1])
        i += 2                         # Don't repeat any concatenated values
    else:
        if (words[i+1] != "-"):
            # If there is no "-" next, append the regular word and tag values
            newWords.append(words[i])
            newTags.append(tags[i])
        i += 1                         # Increment normally
        
# Create output dataframe output_df        
d2 = {'Word': newWords, 'Tag': newTags}
output_df = pd.DataFrame(data=d2)

【问题讨论】:

  • 你所说的“多于一个破折号的行”是什么意思?应该如何解决?
  • @maow 我已经编辑了问题,比如预期输出中的索引号 8

标签: python pandas numpy dataframe merge


【解决方案1】:

我对@9​​87654321@ 的处理方式:

#df['Word'] = df['Word'].str.replace(' ', '') #if necessary
blocks = df['Word'].shift().ne('-').mul(df['Word'].ne('-')).cumsum()
new_df = df.groupby(blocks, as_index=False).agg({'Word' : ''.join, 'Tag' : 'first'})
print(new_df)

输出

                   Word Tag
0                  Asam   O
1   instruksi-instruksi   O
2                bahasa   Y
3   Instruksi-instruksi   P
4                sebuah   Q
5         satuan-satuan   K
6                  meja   W
7             Tiap-tiap   Q
8  karakter-ke-karakter   P

方块(详细)

print(blocks)
0     1
1     2
2     2
3     2
4     3
5     4
6     4
7     4
8     5
9     6
10    6
11    6
12    7
13    8
14    8
15    8
16    9
17    9
18    9
19    9
20    9
Name: Word, dtype: int64

【讨论】:

  • 什么是块?
  • blocks = df['Word'].shift().ne('-').mul(df['Word'].ne('-')).cumsum() pandas.pydata.org/pandas-docs/stable/reference/api/… ,我们在 df.groupby(blocks) 中使用 by = blocks 。为系列blocks 中的每个不同值创建一个组。对于每个组,应用为每列指定的函数。关键是知道如何区分这些群体。
  • 当当前行和上一行都不是“-”时,每个组开始。例如ba-k-a1222
【解决方案2】:

这是一个循环版本:

import pandas as pd
# import data
DF = pd.read_csv("table.csv")
# creates a new DF
newDF = pd.DataFrame()
# iterate through rows
for i in range(len(DF)-1):
    # prepare prev row index (?dealing with private instance of first row)
    prev = i-1
    if (prev < 0):
        prev = 0
    # copy column if the row is not '-' and the next row is not '-'
    if (DF.loc[i+1, 'Word'] != '-'):
        if (DF.loc[i, 'Word'] != '-' and DF.loc[prev, 'Word'] != '-'):
            newDF = newDF.append(DF.loc[i, :])
    # units the three rows if the middle one is '-'
    else:
        row = {'Tag': [DF.loc[i, 'Tag']], 'Word': [DF.loc[i, 'Word']+DF.loc[i+1, 'Word']+DF.loc[i+2, 'Word']]} 
        newDF = newDF.append(pd.DataFrame(row))

【讨论】:

    猜你喜欢
    • 2021-08-06
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 2021-08-19
    • 2016-07-12
    • 1970-01-01
    • 2012-12-29
    相关资源
    最近更新 更多