我的最终目标:我想上传一个新的表格文件(可以是excel、pdf、txt、csv)到主excel电子表格。然后,从主数据表中选出几列,然后用图表将它们按状态分组:这些样本属于X类还是Y类?然后根据每个样本绘制它们
数据方面,我有属于X类或Y类的样本。它们是X或Y,并且具有与样本以及样本计数相关的名称(例如,样本#abc属于类别X,具有30个不同值的计数)
我正在使用pandas打开数据并操作表。这是我的代码中给我带来问题的部分。所有其他问题我都找到了解决办法。这个我不能。我尝试过使用fillna(df_choice.column),但我发现它不能代替NaN。尝试过重置索引或设置索引,但没有真正的帮助。示例输出的X(如果我先输入“X”)或Y(如果我先输入“Y”)为NAN,但其他三列没有问题
df_选项是我从主数据表中选择两列的前一个数据框。在本例中,它将是X列和Y列
df_new= {'X':[], 'Y':[], 'Property of X (units)':[], 'Property of Y (units)':[]} #setup dict
df_new= pd.DataFrame.from_dict(df_new) #dict to df
for df_choice.column in df_choice.columns: #list columns in previous dataset
print(df_choice.column)
state = input('Is this sample considered X or Y? Input X or Y, or quit to exit the loop') #ask if column in previous dataset falls under X or Y
if state == 'quit':
break
elif state == 'x':
df_new['Property of X (units)'] = df_choice[df_choice.column] #takes data from old dataframe into new
df_new['X'] = 'df_choice.column' #fills column X with column name from df_choice
elif state == 'y':
df_new['Y'] = 'df_choice.column'
df_new['Property of Y (units)'] = df_choice[df_choice.column]
else:
print('Not a valid response')
df_new #prints new df
我看到的(仅显示4行,但将每行想象为NaN):
+-----+------------+----------------+----------------+
| X | Y | Property of X | Property of Y |
+-----+------------+----------------+----------------+
| NaN | Sample123 | 4 | 3 |
| NaN | Sample123 | 5 | 4 |
| NaN | Sample123 | 3 | 6 |
| NaN | Sample123 | 4 | 1 |
+-----+------------+----------------+----------------+
我应该得到:
+-----------+------------+----------------+----------------+
| X | Y | Property of X | Property of Y |
+-----------+------------+----------------+----------------+
| SampleABC | Sample123 | 4 | 3 |
| SampleABC | Sample123 | 5 | 4 |
| SampleABC | Sample123 | 3 | 6 |
| SampleABC | Sample123 | 4 | 1 |
+-----------+------------+----------------+----------------+
最后,我假设我想要df_new.melt()来最终绘制它们,按X或Y对条形图或方框图进行分组
+-----------+-------+-----------+
| Sample | Type | Property |
+-----------+-------+-----------+
| SampleABC | X | 4 |
| SampleABC | X | 5 |
| SampleABC | X | 3 |
| SampleABC | X | 4 |
| Sample123 | Y | 3 |
| Sample123 | Y | 4 |
| Sample123 | Y | 6 |
| Sample123 | Y | 1 |
+-----------+-------+-----------+
我已经自学了一个月左右的代码,所以如果我的代码效率低下或者不够聪明,我向你道歉,我会遇到一些问题,看看别人是怎么做的,看看什么对我有用。没有正式的培训,我是一名经过培训的材料科学家。我知道的不多,我想最好的学习方法是掌握一些基础知识,然后做一些对我真正有用的东西
插入空数据帧时,应将列名作为向量传递,而不是单个字符串
可以这样想:通过向空数据帧传递单个字符串,您正在空数据帧中创建一列。但是熊猫怎么知道这个列应该有多长呢
for循环中的变量也有一个令人困惑的名称:“df_choice.column”中的点看起来像是在访问数据帧
综合起来:
请注意,我也替换了“Y”变量的行,以防它出现在“X”之前
要使用np.repeat,请导入库
相关问题 更多 >
编程相关推荐