根据上一行添加新行

2024-03-29 00:06:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

 index    Index_Date    A    B    C    D
 ===========================================
 1        2015-01-31    10   10   we   10
 2        2015-02-01     2    3   jk   22 and 23 and 24 
 3        2015-02-02    10   60   nm   280 and 284
 4        2015-02-03    10  100   oi   250
 5        2015-02-03    10  100   yh  Egyptian and Hittite

我想达到

 index    Index_Date    A    B    C    D
 ===========================================
 1        2015-01-31    10   10   we  10
 2        2015-02-01     2    3   jk  22
 3        2015-02-01     2    3   jk  23
 4        2015-02-01     2    3   jk  24
 5        2015-02-02    10   60   nm  280
 6        2015-02-02    10   60   nm  284
 7        2015-02-03    10  100   oi  250
 8        2015-02-03    10  100   yh  Egyptian
 9        2015-02-03    10  100   yh  Hittite

基本上,程序需要找到and语句,如果找到重复的那一行,那么就把before and部分(22)留在重复行的第一个after and部分(23)和其余部分。你知道吗

我从这个开始,但我不知道我应该去哪里。你知道吗

  for row in df:
        if df['D'].str.contains(' and ', case=True, na=False, regex=True):

我以前也问过更简单的版本。我也不确定这是太难还是太容易。你知道吗


Tags: and数据程序truedfdateindexwe
3条回答

许多方法来微调这个和它的变化已经被问了很多次。你知道吗

D = df.D.astype(str).str.split(' and ')
idx = df.index.repeat(D.str.len())
df.loc[idx].assign(D=np.concatenate(D).astype(int))

   Index_Date   A    B   C    D
0  2015-01-31  10   10  we   10
1  2015-02-01   2    3  jk   22
1  2015-02-01   2    3  jk   23
1  2015-02-01   2    3  jk   24
2  2015-02-02  10   60  nm  280
3  2015-02-03  10  100  oi  250

有一种方法:

import pandas as pd

df = pd.DataFrame([['2015-01-31', 10, 10, 'we', 10],
                   ['2015-02-01', 2, 3, 'jk', '22 and 23 and 24'],
                   ['2015-02-02', 10, 60, 'nm', 280],
                   ['2015-02-03', 10, 100, 'oi', 250]],
                  columns=['Index_Date', 'A', 'B', 'C', 'D'])

df.loc[df.D.astype(str).str.contains('and').fillna(False), 'D'] = df.D.str.split('and')

res = df.set_index(['Index_Date', 'A', 'B', 'C'])['D'].apply(pd.Series).stack().reset_index()
res = res.rename(columns={0: 'D'})
res.D = res.D.astype(int)
res = res[['Index_Date', 'A', 'B', 'C', 'D']]

#    Index_Date   A    B   C    D
# 0  2015-01-31  10   10  we   10
# 1  2015-02-01   2    3  jk   22
# 2  2015-02-01   2    3  jk   23
# 3  2015-02-01   2    3  jk   24
# 4  2015-02-02  10   60  nm  280
# 5  2015-02-03  10  100  oi  250

这里有一个方法

df = pd.read_clipboard(sep = '\s\s+')

Index_Date    A    B    C    D
2015-01-31    10   10   we  10
2015-02-01     2    3   jk  22 and 23 and 24 
2015-02-02    10   60   nm  280
2015-02-03    10  100   oi  250


df.set_index(['Index_Date', 'A', 'B', 'C']).D.str.split('and', expand = True)\
.stack().reset_index(4,drop = True).reset_index(name = 'D')

    Index_Date  A   B   C   D
0   2015-01-31  10  10  we  10
1   2015-02-01  2   3   jk  22
2   2015-02-01  2   3   jk  23
3   2015-02-01  2   3   jk  24
4   2015-02-02  10  60  nm  280
5   2015-02-03  10  100 oi  250

相关问题 更多 >