gpt4 book ai didi

python - 如何迭代 pandas 数据帧行,查找字符串并分成列?

转载 作者:行者123 更新时间:2023-12-02 07:55:05 26 4
gpt4 key购买 nike

所以这是我的问题,我有一个数据框 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()”

有什么帮助吗?谢谢!!

最佳答案

使用Series.where前向填充 state 列的缺失值,为 city 分配 Series s,然后过滤条件 boolean indexing使用 ~ 的反转掩码:

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

如果您愿意,您还可以通过添加 DataFrame.pop 来删除原始列:

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

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

df = df[~m]
print (df)
state city
1 US Boston
2 US Washington
3 US Chicago
5 UK London
6 UK Manchester

关于python - 如何迭代 pandas 数据帧行,查找字符串并分成列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60772846/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com