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

标签 python pandas csv dataframe

我的 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。但出现类型不匹配错误。

最佳答案

这是通过 pd.DataFrame.mask 的矢量化方法:

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

关于python - 查找 CSV(数字)中的特定字段值并将其转换为文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53010380/

相关文章:

python - 亚马逊 mws 访问欧洲市场被拒绝

python - 如何在全局保存 header api

python - 如果存在某些值,如何重新分配具有重复值的列的值?

JAVA:如何自动将唯一ID号写入.CSV文件

sql-server - 将 Excel 和 csv 动态加载到 Sql 服务器

python - CSV 文件 - 合并,如果具有相同值的列执行 :

python - Unicode 字符串的 lxml.etree.XML ValueError

javascript - 如何在 Pyramid/Pylon 中返回 javascript

python - 在 pandas 中使用 openpyxl 编写时损坏的工作簿

python - 在 Spyder 控制台中记录输入和输出