2017-09-21 5 views
1

私はWhatsappの履歴チャットで遊んでいます。 メッセージの列を時間とメッセージの2つの列に分割します。 " - " 区切り文字と2を分割するためにPythonデータフレーム - 文字列を2列に分割

enter image description here

は、私が試した:

history['message'] = pd.DataFrame([line.split(" - ",1) for line in history['message']]) 

しかし、歴史[ 'メッセージ']は唯一の時間となります。

なぜなら、line.split( " - "、1)はせいぜい2つの要素のリストを与えると思います。

答えて

3

私はあなたがリターンDataFrameためexpand=Truestr.splitが必要だと思う:

history = pd.DataFrame({'message':['a - b','c - d - r']}) 

history[['a','b']] = history['message'].str.split(' - ', n=1, expand=True) 
print (history) 
    message a  b 
0  a - b a  b 
1 c - d - r c d - r 

NaNs使用した場合:私にとって

history[['a','b']] = pd.DataFrame([line.split(" - ", 1) for line in history['message']]) 

がエラーを返さない:

history['a'] = pd.DataFrame([line.split(" - ", 1) for line in history['message']]) 
print (history) 

ValueError: Wrong number of items passed 2, placement implies 1

それはあなたのために働くのであれば、セパレーターをチェックしてみてください、splitがないようなので:

サンプル:

history['a'] = history['message'].str.split('^', n=1, expand=True) 
print (history) 
    message   a 
0  a - b  a - b 
1 c - d - r c - d - r 
関連する問題