![](/img/trans.png)
[英]Split timestamp column into two new columns in CSV using python and pandas
[英]Split column into two new columns in Pandas
我有一个具有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'] = 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))
我遇到了同样的error: List index out of range
。 问题出在哪里,这些值是否在某种列表中?
任何一种解决方案都欢迎。 谢谢
您需要split
:
df[['value_left','value_right']] = df['value_1'].str.split(';', expand=True)
print (df)
value_1 value_left \
0 over 1 - 42 -> take this ; over 3 - 4 over 1 - 42 -> take this
1 over 3 - 26 -> take this ; over 3 - 45 over 3 - 26 -> take this
2 over 5 - 25 -> take this ; over 2 - 80 over 5 - 25 -> take this
value_right
0 over 3 - 4
1 over 3 - 45
2 over 2 - 80
样品多次;
-可以指定哪个;
用于拆分:
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
字符串partition
另一种方法,即
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.