Python 将列拆分为熊猫中的两个新列
我有一个数据框,有4列,值如下:Python 将列拆分为熊猫中的两个新列,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据框,有4列,值如下: value_1 over 1 - 42 -> take this ; over 3 - 4 over 3 - 26 -> take this ; over 3 - 45 over 5 - 25 -> take this ; over 2 - 80 我需要通过用“;”拆分,从每一列中生成两列。 当我尝试这个: s = df['value_1'].apply(lambda x: x.split(';')) df['value_left'] =
value_1
over 1 - 42 -> take this ; over 3 - 4
over 3 - 26 -> take this ; over 3 - 45
over 5 - 25 -> take this ; over 2 - 80
我需要通过用“;”拆分,从每一列中生成两列。
当我尝试这个:
s = df['value_1'].apply(lambda x: x.split(';'))
df['value_left'] = s.apply(lambda x: x[0])
df['value_right'] = s.apply(lambda x: x[1])
或者这个:
f['new_value1'] = df['value_1']
df['value_1_right'] = None
df['value_1_right'].update(df.new_band_bandw_1.apply(lambda x: x.str.split(';')[1]
if len(x.str.split()) == 2 else None))
我得到了相同的错误:列表索引超出范围
。问题是,这些值是否可能在某种列表中
任何一种解决方案都是受欢迎的。谢谢您需要:
多个的示例代码>-可以指定哪个代码>用于拆分:
df = pd.DataFrame({
'value_1': ['a;r;e','b;r','c;g;t;e']
})
print (df)
value_1
0 a;r;e
1 b;r
2 c;g;t;e
df[['value_left','value_right']] = df['value_1'].str.split(';', expand=True, n=1)
print (df)
value_1 value_left value_right
0 a;r;e a r;e
1 b;r b r
2 c;g;t;e c g;t;e
你需要:
多个的示例代码>-可以指定哪个代码>用于拆分:
df = pd.DataFrame({
'value_1': ['a;r;e','b;r','c;g;t;e']
})
print (df)
value_1
0 a;r;e
1 b;r
2 c;g;t;e
df[['value_left','value_right']] = df['value_1'].str.split(';', expand=True, n=1)
print (df)
value_1 value_left value_right
0 a;r;e a r;e
1 b;r b r
2 c;g;t;e c g;t;e
字符串分区的另一种方法,即
df[['val1','val2']] = df[0].str.partition(';').iloc[:,0::2]
0 val1 val2
0 over 1 - 42 -> take this ; over 3 - 4 over 1 - 42 -> take this over 3 - 4
1 over 3 - 26 -> take this ; over 3 - 45 over 3 - 26 -> take this over 3 - 45
2 over 5 - 25 -> take this ; over; 2 - 80 over 5 - 25 -> take this over; 2 - 80
字符串分区的另一种方法,即
df[['val1','val2']] = df[0].str.partition(';').iloc[:,0::2]
0 val1 val2
0 over 1 - 42 -> take this ; over 3 - 4 over 1 - 42 -> take this over 3 - 4
1 over 3 - 26 -> take this ; over 3 - 45 over 3 - 26 -> take this over 3 - 45
2 over 5 - 25 -> take this ; over; 2 - 80 over 5 - 25 -> take this over; 2 - 80
哪一行有错误?哪一行有错误?看起来不错,但我有这个;ValueError:列的长度必须与键的长度相同,这意味着存在多个
,因此df['value_1'].str.split(';',expand=True,n=1)
应该help@jezrael你对分区有什么看法?@Dark-这里最好是split
,但是partitions
也可以工作;)我知道要击败分裂的答案并不容易,我只是增加了另一种方式;)看起来不错,但我得到了这个;ValueError:列的长度必须与键的长度相同,这意味着存在多个
,因此df['value_1'].str.split(';',expand=True,n=1)
应该help@jezrael你对分区有什么看法?@Dark-这里最好是split
,但是partitions
也可以工作;)我知道要击败分裂的答案并不容易,我只是增加了另一种方式;)