[英]How to split data of single column to separate columns in pairs
I am using a csv file with dataframe name content
.我正在使用数据框名称content
的 csv 文件。 I am trying this code but it not providing expected output我正在尝试这段代码,但它没有提供预期的输出
new_content1 = content['Value1','Value2','Value3','Value4','Value5','Value6']
def get_pairs(x):
arr = x.split(' ')
return list(map(list, zip(arr, arr[1:])))
new_content1['pairs'] = new_content1.applymap(get_pairs)
new_content1
Value1 Value2 .... pairs(single column) Value1 Value2 .... 对(单列)
0 3 2 2 4 2 2 [[3, 2], [2, 2], [2, 4], [4, 2], [2, 2]] 1 1 2 3 4 5 6 [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] 0 3 2 2 4 2 2 [[3, 2], [2, 2], [2, 4], [4, 2], [2, 2]] 1 1 2 3 4 5 6 [[1, 2] ], [2, 3], [3, 4], [4, 5], [5, 6]]
IIUC, you can simply use: IIUC,您可以简单地使用:
new_content1['pairs'] = new_content1['ColName'].str.split(" ", n = 1, expand = True)
where ColName is column you want to split, it will return a values as list in pairs
column其中 ColName 是您要拆分的列,它将返回一个值作为pairs
列中的列表
Alternatively, if you want the output to make new columns based on splits, eg two columns, you can use the above as:或者,如果您希望输出基于拆分创建新列,例如两列,则可以将上述内容用作:
new_content1[['newCol1', 'newCol2']] = new_content1['ColName'].str.split(" ", n = 1, expand = True)
As per your comment let say you have df
column like this one:根据您的评论,假设您有这样的df
列:
Value
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
if your column are separate then join them using:如果您的列是分开的,则使用以下方法加入它们:
df['Value']=df['value1']+' '+df['value2']+' '+df['value3']+' '+df['value4']+' '+df['value5']+' '+df['value6']
then you can do this那么你可以这样做
df['Value']=df['Value'].astype('str')
df['new']=df['Value'].str.split(' ').apply(lambda x:list((zip(x[:], x[1:]))))
Output looks like this输出看起来像这样
+--------+--------------+------------------------------------------+
| Value | new | pairs |
+--------+--------------+------------------------------------------+
| 0 | 1 2 3 4 5 6 | [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] |
| 1 | 1 2 3 4 5 6 | [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] |
| 2 | 1 2 3 4 5 6 | [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] |
| 3 | 1 2 3 4 5 6 | [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] |
| 4 | 1 2 3 4 5 6 | [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] |
| 5 | 1 2 3 4 5 6 | [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] |
| 6 | 1 2 3 4 5 6 | [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] |
+--------+--------------+------------------------------------------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.