2017-06-16 1 views
2

2つの列を持つpandasデータフレームがあります。df.column.str.containsの使用とpandasデータフレーム列の更新

df= pd.DataFrame({"C": ['this is orange','this is apple','this is pear','this is plum','this is orange'], "D": [0,0,0,0,0]}) 

このCの列を読んで、D列に果物の名前を戻したいと考えています。だから私の思考プロセスでは、df.C.str.containsを使って特定の文字列がCの各行に表示されているかどうかを判断していました.Cの要素は実際には長い文字列である可能性があります。 "これは赤いリンゴです"と言いますが、リンゴという言葉が細胞内に現れた場合にのみ気にします。私はstr.containsを使用することに結びついていないことに注意する必要がありますが、これは私にとって最も明白な道に思えました。どのように私がそれを適用するか分からない。最終データフレームは次のようになります

:あなたは果物が抽出される方法を指定しませんでしたので

df= pd.DataFrame({"C": ['this is orange','this is apple','this is pear','this is plum','this is orange'], "D": ['orange','apple','pear','plum','grapefruit']}) 

答えて

1

あなたが果物の名前を想定した果物の名前はあなたが

C       D 
0 this is orange    orange 
1 this is apple which is red apple 
2 this is pear    pear 
3 this is plum    plum 
4 this is orange    orange 
を取得

df['D'] = df.C.str.extract('this is ([A-Za-z]+)\s?.*?') 

「これは」以下の抽出するために、次のコードを使用することができ、このデータフレーム

df= pd.DataFrame({"C": ['this is orange','this is apple which is red','this is pear','this is plum','this is orange'], "D": [0,0,0,0,0]}) 

    C       D 
0 this is orange    0 
1 this is apple which is red 0 
2 this is pear    0 
3 this is plum    0 
4 this is orange    0 

を考えてみましょう

あなたが投稿したサンプルのデータセットについては、単純なスペースの分割とlaの抽出文章は常にthis isで始まり、すなわちfruit name続く3番目のワードは、常にfruit nameであれば、あなたはまた、データフレームstringの行ごとに分割されるようsplit()機能とともにapplyを使用することができますし、場合番目の要素は

df['D'] = df.C.str.split(' ').str[-1] 
+0

?だから代わりに、それはthisis(オレンジ)のようなものかもしれません。そして私はオレンジ色の言葉だけを返したい。 – John

+0

df.C.str.extract(これは\(?(A-Za-z)+)\ s?。*? ')を使用して、果物の周りのかっこの可能性を扱うことができます。ケース – Vaishali

+0

受け入れていただきありがとうございます:) – Vaishali

1

、私はそれは常に「これは」が先行していることを想定しています。したがって、以下は長い道を行く必要があります。

import pandas as pd 

d = {'C': ['this is orange', 
    'this is apple', 
    'this is pear', 
    'this is plum', 
    'this is orange'], 
'D': [0, 0, 0, 0, 0]} 

dff = pd.DataFrame(d) 

dff['D'] = dff.C.str.replace(r'(this is) ([A-Za-z]+)','\\2') 
# or just 
dff.C.str.replace('this is ','') 


#     C  D 
# 0 this is orange orange 
# 1 this is apple apple 
# 2 this is pear pear 
# 3 this is plum plum 
# 4 this is orange orange 

これは、空の文字列で「これは」交換する.str.replaceを使用しています。

こちらがお役に立てば幸いです。

1

の作品結果の三番目は、カラムDの値を置き換えるために取られる:

df['D'] = df['C'].apply(lambda val: val.split()[2]) 

またはその他の回答では、単にsplit機能、

を述べたように

df['D'] = df['C'].str.split().str[2]

出力:これは完全に質問を変更した場合、私は理解し、再要求されますが、果物は括弧とスペースなしで包まれていた場合はどう

C D 0 this is orange orange 1 this is apple apple 2 this is pear pear 3 this is plum plum 4 this is orange orange

関連する問題