ValueError:列的长度必须与键的长度相同(使用python在多列中拆分列)

时间:2020-04-20 14:03:57

标签: python regex

这个问题已经问了很多,但是我仍然没有找到解决方案。我有一栏看起来像这样

enter image description here enter image description here enter image description here

我想做的是在不同的列中将国家和语言分开,例如

Country    Language 
Vietnam    Vietnamese_display 1
Indonesia  Tamil__1
India      Tamil_Video_5

我正在使用下面的代码来完成它,但是有很多因素需要考虑,我不确定该怎么做

df[['Country', 'Language']] = df['Line Item'].str.split('_\s+', n=1, expand=True)

如何跳过第一个“ _”以获得所需的结果?谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用

jax

请参见regex demo

详细信息

  • df[['Country', 'Language']] = df['Line Item'].str.extract(r'^_*([^_]+)_(.+)') -字符串的开头
  • ^-下划线为0个或更多
  • _*-捕获组1:([^_]+)以外的任何一个或多个字符
  • _-一个_字符
  • _-第2组:除换行符以外的任何一个或多个字符。

熊猫测试:

(.+)