[英]Fetching the first few characters of a column from a csv file using pandas
I have a csv file which contains some data, here I will put some data.我有一个 csv 文件,其中包含一些数据,这里我将放置一些数据。
enter image description here在此处输入图像描述
So, the output should be,所以,output 应该是,
02
04
I have tried these solutions so far,到目前为止,我已经尝试过这些解决方案,
code:代码:
var1 = data.loc[{data["Quantity"] == 10) & (data["Max value"].str[:2] == 40)]
var2 = (var1["ID"].str[:2])
print(var2)
output: output:
Empty DataFrame
Columns: [ID, Quantity, Max value]
Index: []
code:代码:
var1 = data.loc[(data.Quantity == 10) & (data.Max value.str[:2] > 40)].ID.str[:2]
var2 = (var1.ID.str[:2])
print(var2)
output: output:
same output
code:代码:
data.rename(columns = {'Max value':'MaxValue'}, inplace = True)
var1 = data.loc[(data["Quantity"] == 10) & (data["Max value"].str[:2] > 40)]
var2 = (var1["ID"].str[:2])
print(var2)
output: output:
Series([], Name: ID, dtype: object)
This does the job:这是做的工作:
df = pd.read_csv(***csv file path***)
df["Max value num"] = [int(max_val[:2]) for max_val in df["Max value"]]
desired_data = df[(df["Quantity"] == 10) & (df["Max value num"] >= 40)]
desired_data = [id[:2] for id in desired_data["ID"]]
This stores the first 2 characters in a list.这将前 2 个字符存储在列表中。
If you want to print them out like 02 04
, then use this,如果你想像02 04
一样打印出来,那么使用这个,
df = pd.read_csv(***csv file path***)
df["Max value num"] = [int(max_val[:2]) for max_val in df["Max value"]]
desired_data = df[(df["Quantity"] == 10) & (df["Max value num"] >= 40)]
output = ""
for id in desired_data["ID"]:
output += f"{id[:2]} "
output.strip(" ")
For both the codes above, I have added a Max value num
column that stores the numeric part of the values in Max value
.对于上面的两个代码,我都添加了一个Max value num
列,用于存储Max value
value 中值的数字部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.