[英]Iterating through dataframe with pandas and replacing characters
My data frame column named 'Shrinkage' looks like:我的名为“收缩”的数据框列如下所示:
-Shrinkage
-($614)
-$0
-$0
-$0
-$0
-$0
-$0
-$0
-($125)
-$320
-$3,779
($2,482)
With the following code, I am trying to perform multiple actions with a for loop and if statement.使用以下代码,我尝试使用 for 循环和 if 语句执行多个操作。 I would like to iterate through the column and if the object has the character '(' then I want to replace it with the character '-' to make that number negative. As well as finding and replacing the negative numbers, I would like to remove all characters and make the objects into floats to perform math with it.
我想遍历该列,如果 object 具有字符“(”,那么我想将其替换为字符“-”以使该数字为负数。除了查找和替换负数外,我还想删除所有字符并将对象变为浮点数以使用它执行数学运算。
for i in ['Shrinkage']:
if df['Shrinkage'] == '(':
df['Shrinkage'] = df['Shrinkage'].replace({'(': '-'}).astype(float)
df['Shrinkage'] = df['Shrinkage'].replace({'$': '', ')': '', ',': ''})
else:
df['Shrinkage'].replace({'$': '', ',': ''}, regex=True).astype(float)
I am getting a ValueError: The truth value of a Series is ambiguous.我得到一个 ValueError: 系列的真值是不明确的。 Use a.empty, a.bool(), a.item(), a.any() or a.all().
使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
Please understand I am still new to python and haven't got into complex code yet.请理解我对 python 还是新手,还没有进入复杂的代码。 Some help is needed please.
需要一些帮助。
try this, series.replace and use regex to remove un-wanted characters.试试这个, series.replace并使用正则表达式删除不需要的字符。
df['Shrinkage'] = df['Shrinkage'].str.replace("\(|\$|\)|,", "")
print(df['Shrinkage'].astype(float))
output, output,
0 -614.0
1 -0.0
2 -0.0
3 -0.0
4 -0.0
5 -0.0
6 -0.0
7 -0.0
8 -125.0
9 -320.0
10 -3779.0
11 2482.0
Name: Shrinkage, dtype: float64
You can do this:你可以这样做:
df['Shrinkage'] = df['Shrinkage'].str.replace('\$|\)|\,', '')
df['Shrinkage'] = df['Shrinkage'].str.replace('\(', '-')
df['Shrinkage'] = df['Shrinkage'].astype(float)
print(df)
Shrinkage
0 -614.0
1 0.0
2 0.0
3 0.0
4 0.0
5 0.0
6 0.0
7 0.0
8 -125.0
9 320.0
10 3779.0
11 -2482.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.