我有一个示例数据集,该数据集比我的实际数据集小得多,它实际上是一个文本文件,我想以 Pandas 表的形式读取它并对其进行处理:

import pandas as pd
d = {
     'one': ['title1', 'R2G', 'title2', 'K5G', 'title2','R14G', 'title2','R2T','title3', 'K10C', 'title4', 'W7C', 'title4', 'R2G', 'title5', 'K8C']
    }
df = pd.DataFrame(d)

示例数据集如下所示:
df
Out[20]:

      one
0   title1
1      R2G
2   title2
3      K5G
4   title2
5     R14G
6   title2
7      R2T
8   title3
9     K10C
10  title4
11     W7C
12  title4
13     R2G
14  title5
15     K8C

我添加了第二列,称为“值”:
df.insert(1,'value','')
df
Out[22]:
      one      value
0   title1
1      R2G
2   title2
3      K5G
4   title2
5     R14G
6   title2
7      R2T
8   title3
9     K10C
10  title4
11     W7C
12  title4
13     R2G
14  title5
15     K8C

我想先,然后每隔一行将移到“值”列:
      one    value
0   title1    R2G
1   title2    K5G
2   title2    R14G
3   title2    R2T
4   title3    K10C
5   title4    W7C
6   title4    R2G
7   title5    K8C

我想按标题名称先然后按分组,因为同一标题可能有多个值:
     one     value
0   title1    R2G
1   title2    K5G, R14G, R2T
2   title3    K10C
3   title4    W7C , R2G
4   title5    K8C

最佳答案

通过使用iloc和步骤arg切片列来构造新的df:

In [185]:
new_df = pd.DataFrame({'one':df['one'].iloc[::2].values, 'value':df['one'].iloc[1::2].values})
new_df

Out[185]:
      one value
0  title1   R2G
1  title2   K5G
2  title2  R14G
3  title2   R2T
4  title3  K10C
5  title4   W7C
6  title4   R2G
7  title5   K8C

然后,您可以在'one'上添加groupby,并在'value'列上应用lambda,然后仅对值进行join:
In [188]:
new_df.groupby('one')['value'].apply(','.join).reset_index()

Out[188]:
      one         value
0  title1           R2G
1  title2  K5G,R14G,R2T
2  title3          K10C
3  title4       W7C,R2G
4  title5           K8C

关于python - 将每隔一行移到新列并分组pandas python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36181622/

10-12 21:13