Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何迭代数据帧行、查找字符串并分离为列?_Python_Pandas_For Loop - Fatal编程技术网

Python 如何迭代数据帧行、查找字符串并分离为列?

Python 如何迭代数据帧行、查找字符串并分离为列?,python,pandas,for-loop,Python,Pandas,For Loop,这是我的问题,我有一个dataframe df,其中有一列“Info”,如下所示: 0 US[edit] 1 Boston(B1) 2 Washington(W1) 3 Chicago(C1) 4 UK[edit] 5 London(L2) 6 Manchester(L2) 我想把所有包含“[ed]”的字符串放在单独的df['state']列中,剩下的字符串应该放在另一列df['city']中。我也想做一些清理工作,把[]和()中的东西移走。这就是我所尝试的: fo

这是我的问题,我有一个dataframe df,其中有一列“Info”,如下所示:

0 US[edit]  
1 Boston(B1)  
2 Washington(W1)  
3 Chicago(C1)  
4 UK[edit]  
5 London(L2)   
6 Manchester(L2) 
我想把所有包含“[ed]”的字符串放在单独的df['state']列中,剩下的字符串应该放在另一列df['city']中。我也想做一些清理工作,把[]和()中的东西移走。这就是我所尝试的:

for ind, row in df.iterrows():
    if df['Info'].str.contains('[ed', regex=False):
        df['state']=df['info'].str.split('\[|\(').str[0]
    else:
        df['city']=df['info'].str.split('\[|\(').str[0]
最后我想要这样的东西

US Boston  
US Washington  
US Chicago  
UK London     
UK Manchester  
当我尝试这样做时,我总是得到“序列的真值是不明确的。使用a.empty、a.bool()、a.item()、a.any()或a.all()

有什么帮助吗?谢谢

用于向前填充
状态
列的缺失值,用于
城市
分配序列s,然后 使用反转遮罩按过滤方式
~

m = df['Info'].str.contains('[ed', regex=False)
s = df['Info'].str.split('\[|\(').str[0]

df['state'] = s.where(m).ffill()
df['city'] = s

df = df[~m]
print (df)
             Info state        city
1      Boston(B1)    US      Boston
2  Washington(W1)    US  Washington
3     Chicago(C1)    US     Chicago
5      London(L2)    UK      London
6  Manchester(L2)    UK  Manchester
如果需要,还可以通过添加以下内容删除原始列:

我会:

s = df.Info.str.extract('([\w\s]+)(\[edit\])?')

df['city'] = s[0]
df['state'] = s[0].mask(s[1].isna()).ffill()
df = df[s[1].isna()]
输出:

                Info        city state
1  1      Boston(B1)      Boston    US
2  2  Washington(W1)  Washington    US
3  3     Chicago(C1)     Chicago    US
5  5      London(L2)      London    UK
6  6  Manchester(L2)  Manchester    UK

这是非常有用的,它的工作,谢谢!你有时间把~的意思解释成“df=df[~m]”吗?我试图删除运算符,但看起来行的顺序不同……我查看了python文档,他们说“它返回一个数字的二进制补码。”……谢谢@FedePy-当然,这意味着您希望通过假值进行选择。因此,取而代之的是
df[m==False]
使用
df[~m]
——它将False替换为
True
,将
True
替换为
False
,因此
df[~m]
df[m==False]相同
                Info        city state
1  1      Boston(B1)      Boston    US
2  2  Washington(W1)  Washington    US
3  3     Chicago(C1)     Chicago    US
5  5      London(L2)      London    UK
6  6  Manchester(L2)  Manchester    UK