簡體   English   中英

根據條件在單個熊貓列中合並數據

[英]Merging data in a single pandas column based on criteria

我有一個熊貓數據框,其中包含大量數據,如下所示:

temp_col
matt
joes\crabshack\one23
fail
joe:123,\
12345678,\
92313456,\
12341239123432,\
1321143
john
jacob
joe(x):543,\
9876544123,\
1234

怎樣才能將所有以“,\\”結尾的數據和其余的沒有一個的數據合並為一行呢?

預期產量:

temp_col
matt
joes\crabshack\one23
fail
joe:1231234567892313456123412391234321321143
john
jacob
joe(x):54398765441231234

您可以嘗試以下方法:

(df.temp_col.groupby((~df.temp_col.str.contains(r",\\$")).shift().fillna(True).cumsum())
 .apply(lambda x: "".join(x.str.rstrip(r",\\"))))

#temp_col
#1                                            matt
#2                            joes\crabshack\one23
#3                                            fail
#4    joe:1231234567892313456123412391234321321143
#5                                            john
#6                                           jacob
#7                        joe(x):54398765441231234
#Name: temp_col, dtype: object

分解

1)創建一個組變量,當元素不以,\\結尾時,將在其中生成新組:

g = (~df.temp_col.str.contains(r",\\$")).shift().fillna(True).cumsum()
g
#0     1
#1     2
#2     3
#3     4
#4     4
#5     4
#6     4
#7     4
#8     5
#9     6
#10    7
#11    7
#12    7
#Name: temp_col, dtype: int64

2)定義一個join函數,以去除逗號和反斜杠;

join_clean = lambda x: "".join(x.str.rstrip(r",\\"))

3)將join函數應用於每個組以連接以,\\結尾的連續行:

df.temp_col.groupby(g).apply(join_clean)

#temp_col
#1                                            matt
#2                            joes\crabshack\one23
#3                                            fail
#4    joe:1231234567892313456123412391234321321143
#5                                            john
#6                                           jacob
#7                        joe(x):54398765441231234
#Name: temp_col, dtype: object

由於數據已包裝(我假設您在其中看到此“ \\”,因此它是同一單元格的一部分。那么它只是一個逗號分隔的數字。

df.columnnamehere.str.split(',').str.join(sep='')

或者“ \\”是一個實際字符,而不僅僅是格式化

df.columnnamehere.str.split(',\').str.join(sep='')

我認為在將數據加載到Pandas DataFrame之前(或何時)進行處理是更好的樣式。 但是,如果您堅持要這樣做,請嘗試以下操作:

from pandas import DataFrame
df = DataFrame({'x': [
'matt', 
'joes\crabshack\one23',
'fail',
'joe:123,\\',
'12345678,\\',
'92313456,\\',
'12341239123432,\\',
'1321143',
'john',
'jacob',
'joe(x):543,\\',
'9876544123,\\'
'1234']})
df['g'] = (1 - df['x'].str.endswith('\\').astype(int).shift().fillna(0)).cumsum()
df = df.groupby('g')['x'].sum().apply(lambda x: x.replace('\\', ''))
df

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM