我正在尝试从数据框中删除列,但无法正常工作。
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)
new_df
应该保留数据和列的名称,性别和年龄。
答案 0 :(得分:0)
假设您要删除
您可以通过两种方式进行操作。
import pandas as pd df=pd.read_csv('filename') df=df.drop(columns=["a","b"])
2。通过选择仅您要显示的列
import pandas as pd
df=pd.read_csv('filename')
new_df=df[["name","sex","age"]]
以您的情况
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]
答案 1 :(得分:0)
Suyash的答案应该起作用。如果您有要放入字符串的列列表,则需要在拆分后注意去除空格。
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