在CSV(数字)中查找特定字段值并将其转换为文本值

2024-09-22 10:30:14 发布

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

我的CSV文件的格式如下:

sidebars,notes,riskOthers,seriousEvents,goodCatches,harms
,SAFE; 2 moveouts; 0 discharges; ED patient awaiting bed in MAT,0,0,0,0
,Staffing,0,0,0,0
,,1,0,0,0
,,0,0,0,0
,,0,0,0,0
,Staffing needs,0,0,0,0
,Safe,1,0,0,0
,1- 1-1/ Staffing @ 3p- 7a,0,0,0,0
SB- Central Stores,,2,0,0,0
SB - ED Dr. G,,0,0,0,0
,,0,0,0,0
,1 pt in restraints,0,0,0,0
,1 Pt in Restraints,0,0,0,0
SB- Pharmacy,@ Risk - Staffing/ Security with Pt who had drug paraphernalia/ 1-1-1,1,0,0,0

我想选择最后四列中大于1的值并用1替换它们。这是我尝试过但失败的代码

data = pd.read_csv('reordered.csv')
df = pd.DataFrame(data, columns = ['sidebars','notes','riskOthers','seriousEvents', 'goodCatches', 'harms'])

# Values to find and their replacements
findL = ['3', '2', '4', '5', '6']
replaceL = ['1', '1', '1', '1', '1']

# Select column (can be A,B,C,D)
col = 'riskOthers';

# Find and replace values in the selected column
df[col] = df[col].replace(findL, replaceL)

在这里,在这段代码中,我试图将所有大于1的值替换为1。但是我得到了类型不匹配错误


Tags: 代码inptdfdatacolsbnotes
2条回答

以下是通过^{}的矢量化方法:

values = df.iloc[:, -4:]
df.iloc[:, -4:] = values.mask(values > 1, 1)

print(df.iloc[:, -4:])

    riskOthers  seriousEvents  goodCatches  harms
0            0              0            0    0.0
1            0              0            0    0.0
2            1              0            0    0.0
3            0              0            0    0.0
4            0              0            0    0.0
5            0              0            0    0.0
6            1              0            0    0.0
7            0              0            0    0.0
8            1              0            0    0.0
9            0              0            0    0.0
10           0              0            0    0.0
11           0              0            0    0.0
12           0              0            0    0.0
13           1              0            0    NaN

尝试映射df[col]并应用lambda函数。 例如:

df[col].map(lambda x: 1 if x > 1 else 0)

相关问题 更多 >