我有2个数据帧df和ndf需要在2列上连接。这与1:1的使用加入不同
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
myst="""india / gujarat, 22905034 , 19:44
india / kerala, 1905094 , 19:33
india / madhya pradesh, 905154 , 21:56
"""
u_cols=['country_state', 'index', 'current_tm']
myf = StringIO(myst)
import pandas as pd
df = pd.read_csv(StringIO(myst), sep=',', names = u_cols)
myst="""india , Gujrat, high
india , KERALA , high
india , madhya pradesh, low
india, bihar, low
"""
u_cols=['country', 'state', 'progress']
myf = StringIO(myst)
import pandas as pd
ndf = pd.read_csv(StringIO(myst), sep=',', names = u_cols)
预期结果看起来像这样......
country state progress index current_tm
india Gujrat high 22905034 19:44
india KERALA high 1905094 19:33
india madhya pradesh low 905154 21:56
india bihar low
此数据框由最终用户提供,可能包含非有效格式,例如india / abc / xyz 有没有办法连接多列的单个列?
更新:
这与我想要达到的目标很接近。
df=df.join(df['branch_name'].str.split('/', expand=True))
有没有办法以这样的方式扩展它只会分成2列?例如如果字符串是a / b / c那么a应该在一列中而b / c应该在另一列中?
答案 0 :(得分:1)
使用
In [232]: dfs = df.country_state.str.split(' / ').str[1]
In [233]: ndfs = ndf.state.str.lower().str.strip()
In [234]: pd.merge(df, ndf, left_on=dfs, right_on=ndfs,
how='right').drop('country_state', 1)
Out[234]:
index current_tm country state progress
0 1905094.0 19:33 india KERALA high
1 905154.0 21:56 india madhya pradesh low
2 NaN NaN india Gujrat high
3 NaN NaN india bihar low