[英]Dropping pandas dataframe columns
I am trying to drop columns from a dataframe but not working.我试图从数据框中删除列但不起作用。
columns_to_retain = 'name, sex, age' # a string of columns
# which will not be dropped
# from the dataframe
x_cols = columns_to_retain.split(',')
new_df = df.drop(columns = not x_cols)
The new_df
should retain the data and columns name, sex and age. new_df
应保留数据和列名称、性别和年龄。
Suppose you want to drop You can do this in two ways.假设您要删除您可以通过两种方式执行此操作。
import pandas as pd df=pd.read_csv('filename') df=df.drop(columns=["a","b"])
2.By selecting only the columns you want to display 2.通过只选择要显示的列
import pandas as pd
df=pd.read_csv('filename')
new_df=df[["name","sex","age"]]
In your case在你的情况下
columns_to_retain = 'name, sex, age'
x_cols = [col.strip() for col in columns_to_retain.split(',')]#column.strip ensures that that are no leading or trailing white space in the words
new_df=df[x_cols]
Suyash's answer should work. Suyash 的回答应该有效。 If you have the list of columns to drop in a string, you would need to take care of stripping the white-spaces after splitting.如果您有要放入字符串的列列表,则需要注意在拆分后去除空格。
df = pd.DataFrame([[4, 5, 5], [4,6,7]], columns=['a', 'b', 'c'])
to_drop = 'b, c'
to_drop_stripped = [x.strip() for x in to_drop.split(',')]
df.drop(columns=to_drop_stripped)
Result:
a
0 4
1 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.