将append()与航向位置==语句Pandas Python

2024-05-23 17:31:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望在下面的代码中添加第二个条件,在文本之前附加一个字符串“Other”。我尝试将它赋给一个变量,并在代码中调用它,但没有成功。这样做的原因是,在创建报告时,我们可以在同一个可视化中调查所有“其他人”,而不是与主工作列分开

 import pandas as pd
 import os
 os.chdir('/Users/')
 df = pd.read_csv("file.csv", encoding = "ISO-8859-1")

df()
Job?     Other
Hitman   NaN
King     NaN
Other    Farmer
# Replace all 'Others with values from the other subsequent other column' 
#Other columns dropped later on in code.
df.loc[df['Job?'] == 'Other', 'Are you?'] = df['If Other: Job?']

在这之前写一个for语句来更改并在以后使用切片会更好吗?如果是这样的话会是这样吗?在

^{pr2}$

编辑以获得更清晰的效果:

我想要的是结果农民出现(或接近)

Job
Hitman
King
Other: Farmer 

耶兹雷尔的进一步编辑:

如果我有多个列,如下所示

Job, Other_1, Position, Other_2, Education, Other_3,
A    NaN      A         NaN      A          Nan
Other Farmer  Other     CEO      Other      Github



 #a for loop like the following:
   for row in df.loc(["Other_1", "Other_2", "Other_3"], axis=1):
    df[row] = df[row].append("other ")

Tags: csv代码importdfforosjobnan
1条回答
网友
1楼 · 发布于 2024-05-23 17:31:14

我认为您需要用连接列按条件替换值:

df.loc[df['Job?'] == 'Other', 'Job?'] = df['Job?'] + ': ' + df['Other']

或使用^{}

^{pr2}$

或使用^{}

df['Job?'] = df['Job?'].mask(df['Job?'] == 'Other', df['Job?'] + ': ' + df['Other'])

df = df.drop('Other', axis=1)
print (df)
            Job?
0         Hitman
1           King
2  Other: Farmer

也可以添加自定义字符串,只删除df['Job?']

df['Job?'] = df['Job?'].mask(df['Job?'] == 'Other', 'ooother: ' + df['Other'])
#last remove column if necessary
df = df.drop('Other', axis=1)
print (df)
              Job?
0           Hitman
1             King
2  ooother: Farmer

编辑:

我认为您可以创建dictionary列和循环应用解决方案:

d = {'Job':'Other_1', 'Position':'Other_2', 'Education':'Other_3'}

for k,v in d.items():
    df[k] = df[k].mask(df[k] == 'Other', 'other: ' + df[v])

df = df.drop(list(d.values()), axis=1)
print (df)
             Job    Position      Education
0              A           A              A
1  other: Farmer  other: CEO  other: Github

相关问题 更多 >